diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..b4a3783
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,205 @@
+# Created by .ignore support plugin (hsz.mobi)
+### Example user template template
+### Example user template
+
+# IntelliJ project files
+.idea
+*.iml
+out
+gen
+### Python template
+# 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/
+pip-wheel-metadata/
+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
+.hypothesis/
+.pytest_cache/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+.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
+
+# celery beat schedule file
+celerybeat-schedule
+
+# 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/
+
+### JetBrains template
+# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
+# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
+
+# User-specific stuff
+.idea/**/workspace.xml
+.idea/**/tasks.xml
+.idea/**/usage.statistics.xml
+.idea/**/dictionaries
+.idea/**/shelf
+
+# Generated files
+.idea/**/contentModel.xml
+
+# Sensitive or high-churn files
+.idea/**/dataSources/
+.idea/**/dataSources.ids
+.idea/**/dataSources.local.xml
+.idea/**/sqlDataSources.xml
+.idea/**/dynamic.xml
+.idea/**/uiDesigner.xml
+.idea/**/dbnavigator.xml
+
+# Gradle
+.idea/**/gradle.xml
+.idea/**/libraries
+
+# Gradle and Maven with auto-import
+# When using Gradle or Maven with auto-import, you should exclude module files,
+# since they will be recreated, and may cause churn. Uncomment if using
+# auto-import.
+# .idea/modules.xml
+# .idea/*.iml
+# .idea/modules
+# *.iml
+# *.ipr
+
+# CMake
+cmake-build-*/
+
+# Mongo Explorer plugin
+.idea/**/mongoSettings.xml
+
+# File-based project format
+*.iws
+
+# IntelliJ
+out/
+
+# mpeltonen/sbt-idea plugin
+.idea_modules/
+
+# JIRA plugin
+atlassian-ide-plugin.xml
+
+# Cursive Clojure plugin
+.idea/replstate.xml
+
+# Crashlytics plugin (for Android Studio and IntelliJ)
+com_crashlytics_export_strings.xml
+crashlytics.properties
+crashlytics-build.properties
+fabric.properties
+
+# Editor-based Rest Client
+.idea/httpRequests
+
+# Android studio 3.1+ serialized cache file
+.idea/caches/build_file_checksums.ser
+.gitignore
+.idea/
diff --git a/.idea/IB-Trading-Models-And-Backtester.iml b/.idea/IB-Trading-Models-And-Backtester.iml
new file mode 100644
index 0000000..7a164c4
--- /dev/null
+++ b/.idea/IB-Trading-Models-And-Backtester.iml
@@ -0,0 +1,15 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml
new file mode 100644
index 0000000..426b3de
--- /dev/null
+++ b/.idea/inspectionProfiles/Project_Default.xml
@@ -0,0 +1,14 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/markdown-navigator.xml b/.idea/markdown-navigator.xml
new file mode 100644
index 0000000..6b82ce2
--- /dev/null
+++ b/.idea/markdown-navigator.xml
@@ -0,0 +1,86 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/markdown-navigator/profiles_settings.xml b/.idea/markdown-navigator/profiles_settings.xml
new file mode 100644
index 0000000..db06266
--- /dev/null
+++ b/.idea/markdown-navigator/profiles_settings.xml
@@ -0,0 +1,3 @@
+
+
+
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644
index 0000000..bc96357
--- /dev/null
+++ b/.idea/misc.xml
@@ -0,0 +1,27 @@
+
+
+
+
+
+
+
+
+
+
+
+ Python
+
+
+ Spelling
+
+
+
+
+ SpellCheckingInspection
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
new file mode 100644
index 0000000..ed55299
--- /dev/null
+++ b/.idea/modules.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 0000000..94a25f7
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/Backtester/Backtester.py b/src/Backtester/Backtester.py
index 3718541..76cccaa 100644
--- a/src/Backtester/Backtester.py
+++ b/src/Backtester/Backtester.py
@@ -1,7 +1,13 @@
-#######################################
+# --------------------------------------------------------
# Author: James Ma
# Email stuff here: jamesmawm@gmail.com
-#######################################
+#
+# Developed and updated by Joseph Loss on 6/19/2019
+# MS Financial Engineering
+# University of Illinois at Urbana-Champaign
+#
+# Inquiries: loss2@illinois.edu
+# --------------------------------------------------------
from ibHFT import IbHFT
from StubTickEvent import StubTickEvent as TickEvent
@@ -36,7 +42,7 @@ def start_data_stream(self, on_started_func, on_tick, stock_codes, on_pos_change
self.report_backtest_results()
def report_backtest_results(self):
- print "Back results:"
+ print("Back results:")
position = {k: 0 for k in self.stock_codes}
pnl = 0
@@ -51,7 +57,7 @@ def report_backtest_results(self):
position[stock_code] += qty * (1 if is_buy else -1)
pnl += mkt_value * (1 if not is_buy else -1) - comm
- print order.filled_time, stock_code, price, "B" if order.is_buy else "S", qty, position[stock_code], pnl
+ print(order.filled_time, stock_code, price, "B" if order.is_buy else "S", qty, position[stock_code], pnl)
def get_commission(self, qty):
return max(1, self.COST_PER_SHARE*qty)
diff --git a/src/Backtester/StubOrderEvent.py b/src/Backtester/StubOrderEvent.py
index 0d98328..d821463 100644
--- a/src/Backtester/StubOrderEvent.py
+++ b/src/Backtester/StubOrderEvent.py
@@ -1,8 +1,13 @@
-#######################################
+# --------------------------------------------------------
# Author: James Ma
# Email stuff here: jamesmawm@gmail.com
-#######################################
-
+#
+# Developed and updated by Joseph Loss on 6/19/2019
+# MS Financial Engineering
+# University of Illinois at Urbana-Champaign
+#
+# Inquiries: loss2@illinois.edu
+# --------------------------------------------------------
class StubOrderEvent:
diff --git a/src/Backtester/StubTickEvent.py b/src/Backtester/StubTickEvent.py
index f0a9001..6599844 100644
--- a/src/Backtester/StubTickEvent.py
+++ b/src/Backtester/StubTickEvent.py
@@ -1,8 +1,13 @@
-#######################################
+# --------------------------------------------------------
# Author: James Ma
# Email stuff here: jamesmawm@gmail.com
-#######################################
-
+#
+# Developed and updated by Joseph Loss on 6/19/2019
+# MS Financial Engineering
+# University of Illinois at Urbana-Champaign
+#
+# Inquiries: loss2@illinois.edu
+# --------------------------------------------------------
class StubTickEvent:
diff --git a/src/Backtester/__init__.py b/src/Backtester/__init__.py
deleted file mode 100755
index e69de29..0000000
diff --git a/src/StockOrder.py b/src/StockOrder.py
index 03016de..eeff95b 100644
--- a/src/StockOrder.py
+++ b/src/StockOrder.py
@@ -1,7 +1,13 @@
-#######################################
+# --------------------------------------------------------
# Author: James Ma
# Email stuff here: jamesmawm@gmail.com
-#######################################
+#
+# Developed and updated by Joseph Loss on 6/19/2019
+# MS Financial Engineering
+# University of Illinois at Urbana-Champaign
+#
+# Inquiries: loss2@illinois.edu
+# --------------------------------------------------------
from ibUtil import *
diff --git a/src/StockPosition.py b/src/StockPosition.py
index 18afe5b..c8380c4 100644
--- a/src/StockPosition.py
+++ b/src/StockPosition.py
@@ -1,7 +1,13 @@
-#######################################
+# --------------------------------------------------------
# Author: James Ma
# Email stuff here: jamesmawm@gmail.com
-#######################################
+#
+# Developed and updated by Joseph Loss on 6/19/2019
+# MS Financial Engineering
+# University of Illinois at Urbana-Champaign
+#
+# Inquiries: loss2@illinois.edu
+# --------------------------------------------------------
from ibUtil import *
diff --git a/src/StockTradable.py b/src/StockTradable.py
index 0513993..436073d 100644
--- a/src/StockTradable.py
+++ b/src/StockTradable.py
@@ -1,7 +1,13 @@
-#######################################
+# --------------------------------------------------------
# Author: James Ma
# Email stuff here: jamesmawm@gmail.com
-#######################################
+#
+# Developed and updated by Joseph Loss on 6/19/2019
+# MS Financial Engineering
+# University of Illinois at Urbana-Champaign
+#
+# Inquiries: loss2@illinois.edu
+# --------------------------------------------------------
class StockTick:
def __init__(self):
diff --git a/src/Strat-CorrelRptr.py b/src/Strat-CorrelRptr.py
index c921027..c7b0bac 100644
--- a/src/Strat-CorrelRptr.py
+++ b/src/Strat-CorrelRptr.py
@@ -1,11 +1,16 @@
-#######################################
+# --------------------------------------------------------
# Author: James Ma
# Email stuff here: jamesmawm@gmail.com
-#######################################
+#
+# Developed and updated by Joseph Loss on 6/19/2019
+# MS Financial Engineering
+# University of Illinois at Urbana-Champaign
+#
+# Inquiries: loss2@illinois.edu
+# --------------------------------------------------------
-""" Strategy: Correlation Reporter
-
-Prints the correlations using Pandas.
+""" Strategy: Correlation Reporter:
+ Prints the correlations using Pandas.
"""
import pandas as pd
@@ -24,7 +29,7 @@ def __init__(self):
return
def process_historical_data(self, msg):
- print msg
+ print(msg)
vwap = msg.WAP
stock_index = msg.reqId
@@ -44,7 +49,7 @@ def process_historical_data(self, msg):
def on_completion(self):
self.ibhft.set_is_shutdown()
- print self.pd_last_prices.corr()
+ print(self.pd_last_prices.corr())
def run(self):
self.ibhft = ibHFT.IbHFT()
@@ -54,5 +59,7 @@ def run(self):
, self.interval
, self.process_historical_data)
+
if __name__ == '__main__':
- TradingStrategy().run()
\ No newline at end of file
+ TradingStrategy().run()
+
diff --git a/src/Strat-Empty.py b/src/Strat-Empty.py
index 946b074..456cf18 100644
--- a/src/Strat-Empty.py
+++ b/src/Strat-Empty.py
@@ -1,11 +1,16 @@
-#######################################
+# --------------------------------------------------------
# Author: James Ma
# Email stuff here: jamesmawm@gmail.com
-#######################################
-
-""" Template Strategy
-
-An empty template to create strategies.
+#
+# Developed and updated by Joseph Loss on 6/19/2019
+# MS Financial Engineering
+# University of Illinois at Urbana-Champaign
+#
+# Inquiries: loss2@illinois.edu
+# --------------------------------------------------------
+
+""" Template Strategy:
+ An empty template to create strategies.
"""
import Backtester.Backtester as bt
@@ -22,10 +27,10 @@ def __init__(self):
return
def on_position_changed(self):
- print "on position changed."
+ print("on position changed.")
def on_tick(self, ticks, stock_code, field_type):
- print "tick"
+ print("tick")
def on_started(self):
return
@@ -40,12 +45,13 @@ def run(self):
def run_backtest(self):
self.ibhft = bt.Backtester()
- self.ibhft.set_csv_file("ticks 10 mins - Jun 25 2014.csv")
+ self.ibhft.set_csv_file("C:\\Users\\jloss\\PyCharmProjects\\IB-Trading-Models-And-Backtester\\src\\ticks 10 mins - Jun 25 2014.csv")
self.ibhft.start_data_stream(self.on_started
, self.on_tick
, STOCKS_TO_STREAM
, self.on_position_changed)
+
if __name__ == '__main__':
# TradingStrategy().run()
- TradingStrategy().run_backtest()
\ No newline at end of file
+ TradingStrategy().run_backtest()
diff --git a/src/Strat-LmtOrdrs.py b/src/Strat-LmtOrdrs.py
index 8738a0e..2506621 100644
--- a/src/Strat-LmtOrdrs.py
+++ b/src/Strat-LmtOrdrs.py
@@ -1,16 +1,22 @@
-#######################################
+# --------------------------------------------------------
# Author: James Ma
# Email stuff here: jamesmawm@gmail.com
-#######################################
-
-""" Strategy: Limit Orders
-
-Place limit orders just above the bid ask prices.
-Close position when exceed certain thresholds.
+#
+# Developed and updated by Joseph Loss on 6/19/2019
+# MS Financial Engineering
+# University of Illinois at Urbana-Champaign
+#
+# Inquiries: loss2@illinois.edu
+# --------------------------------------------------------
+
+""" Strategy: Limit Orders:
+ 1. Place limit orders just above the bid ask prices.
+ 2. Close position when exceed certain thresholds.
"""
-import Backtester.Backtester as bt
-from Tkinter import *
+import tkinter
+import ipywidgets
+from Backtester import *
import ibHFT
# Fixed params
@@ -41,16 +47,16 @@ def __init__(self):
self.tx_px = self.limit_px = self.loss_px = 0
self.current_cycle = 0
self.current_sampling_thread = None
- self.tk = Tk()
- self.label_stock = StringVar()
- self.label_bidask = StringVar()
- self.label_last = StringVar()
- self.label_ticks = StringVar()
- self.label_position = StringVar()
- self.label_orders = StringVar()
- self.label_pnl = StringVar()
- self.label_cycle = StringVar()
- self.label_traded = StringVar()
+ self.tk = tkinter.Tk()
+ self.label_stock = tkinter.StringVar()
+ self.label_bidask = tkinter.StringVar()
+ self.label_last = tkinter.StringVar()
+ self.label_ticks = tkinter.StringVar()
+ self.label_position = tkinter.StringVar()
+ self.label_orders = tkinter.StringVar()
+ self.label_pnl = tkinter.StringVar()
+ self.label_cycle = tkinter.StringVar()
+ self.label_traded = tkinter.StringVar()
return
def on_tick(self, ticks, stock_code, field_type):
@@ -164,7 +170,7 @@ def on_position_changed(self):
else:
self.current_state = self.STATE_TERMINATED
self.tk.quit()
- print "Cycle completed."
+ print("Cycle completed.")
def is_no_open_orders(self):
num_open_orders = self.ibhft.get_number_of_pending_orders()
@@ -227,13 +233,13 @@ def update_ui(self):
, loss=self.loss_px)
self.label_traded.set(tradedstr)
- def create_ui(self):
+ def create_ui(self):
def create_row(header, label, row):
- Label(self.tk, text=header).grid(row=row,column=0)
- Label(self.tk, textvariable=label).grid(row=row,column=1)
+ tkinter.Label(self.tk, text=header).grid(row=row, column=0)
+ tkinter.Label(self.tk, textvariable=label).grid(row=row, column=1)
row += 1
- return row
+ return row_index
row_index = 0
row_index = create_row("Stock:", self.label_stock, row_index)
@@ -262,13 +268,14 @@ def run(self):
, self.on_position_changed)
def run_backtest(self):
- self.ibhft = bt.Backtester()
- self.ibhft.set_csv_file("ticks 10 mins - Jun 25 2014.csv")
+ self.ibhft = Backtester()
+ self.ibhft.set_csv_file("C:\\Users\\jloss\\PyCharmProjects\\IB-Trading-Models-And-Backtester\\src\\ticks 10 mins - Jun 25 2014.csv")
self.ibhft.start_data_stream(self.on_started
, self.on_tick
, STOCKS_TO_STREAM
, self.on_position_changed)
if __name__ == '__main__':
- TradingStrategy().run()
- # TradingStrategy().run_backtest()
\ No newline at end of file
+ # TradingStrategy().run()
+ TradingStrategy().run_backtest()
+
diff --git a/src/Strat-Pairs.py b/src/Strat-Pairs.py
index 8449881..9e1ed0a 100644
--- a/src/Strat-Pairs.py
+++ b/src/Strat-Pairs.py
@@ -1,18 +1,28 @@
-#######################################
+# --------------------------------------------------------
# Author: James Ma
# Email stuff here: jamesmawm@gmail.com
-#######################################
+#
+# Developed and updated by Joseph Loss on 6/19/2019
+# MS Financial Engineering
+# University of Illinois at Urbana-Champaign
+#
+# Inquiries: loss2@illinois.edu
+# --------------------------------------------------------
""" Strategy: Pairs trading through cointegration
+ Uses OLS to determine order of co-integration every self.window_length.
-Uses OLS to determine order of co-integration every self.window_length.
-Pair-trading by mean-reversion.
+ Pair-trading by mean-reversion.
"""
-import Backtester.Backtester as bt
+import tkinter
+from Backtester import *
import pandas as pd
-from pandas.stats.api import ols
-from Tkinter import *
+
+# from statsmodels.api import OLS as ols
+from statsmodels.api import OLS
+import statsmodels.formula.api as smf
+import statsmodels as sm
import ibHFT
import threading
import ibDataTypes
@@ -48,16 +58,16 @@ def __init__(self):
self.current_cycle = 0
self.current_sampling_thread = None
self.pd_last_prices = pd.DataFrame()
- self.tk = Tk()
- self.label_stock = StringVar()
- self.label_bidask = StringVar()
- self.label_last = StringVar()
- self.label_ticks = StringVar()
- self.label_position = StringVar()
- self.label_orders = StringVar()
- self.label_pnl = StringVar()
- self.label_zscore = StringVar()
- self.label_traded = StringVar()
+ self.tk = tkinter.Tk()
+ self.label_stock = tkinter.StringVar()
+ self.label_bidask = tkinter.StringVar()
+ self.label_last = tkinter.StringVar()
+ self.label_ticks = tkinter.StringVar()
+ self.label_position = tkinter.StringVar()
+ self.label_orders = tkinter.StringVar()
+ self.label_pnl = tkinter.StringVar()
+ self.label_zscore = tkinter.StringVar()
+ self.label_traded = tkinter.StringVar()
self.spreads = []
self.window_length = 30
self.is_bootstrapped = False
@@ -87,7 +97,7 @@ def on_tick(self, ticks, stock_code, field_type):
self.current_ticks = ticks
if not self.is_bootstrapped:
- print "Bootstrapping...."
+ print("Bootstrapping....")
return
[stock_code_a, stock_code_b, stock_code_c] = STOCKS_TO_STREAM
@@ -144,11 +154,26 @@ def on_tick(self, ticks, stock_code, field_type):
self.update_ui(zscore)
+ from pandas import DataFrame
+
def get_coeffs_from_ols(self, a, b):
- slope, intercept = ols(y=a, x=b).beta[['x', 'intercept']]
- spreads_pair_ab = self.calculate_spread(a, b, slope, intercept)
- mean, stdev = self.get_mean_and_std(spreads_pair_ab)
- return slope, intercept, mean, stdev
+ model = OLS(a,b,missing = 'none',hasconst = 'yes').fit()
+ model.summary()
+
+ # [['x', 'intercept']]
+ # sm.tools.add_constant('b')
+ # results = smf.ols('a ~ b').fit()
+ # smf.OLS.fit(self,"pinv",cov_type = )
+ # slope, intercept = OLS(endog=a, exog=b)
+ # ['x','intercept']
+ # result = model.fit()
+ # sm.tools.add_constant[['x', 'intercept']]
+ # self.
+ # slope, intercept = OLS(endog=a, exog=b).fit_regularized[['x','intercept']]
+ # slope, intercept = OLS(
+ # spreads_pair_ab = self.calculate_spread(a, b, slope, intercept)
+ # mean, stdev = self.get_mean_and_std(spreads_pair_ab)
+ # return slope, intercept, mean, stdev
@staticmethod
def get_mean_and_std(values):
@@ -184,7 +209,7 @@ def on_position_changed(self):
else:
self.current_state = self.STATE_TERMINATED
self.tk.quit()
- print "Cycle completed."
+ print("Cycle completed.")
def is_no_open_orders(self):
num_open_orders = self.ibhft.get_number_of_pending_orders()
@@ -245,8 +270,8 @@ def update_ui(self, zscore):
def create_ui(self):
def create_row(header, label, row):
- Label(self.tk, text=header).grid(row=row,column=0)
- Label(self.tk, textvariable=label).grid(row=row,column=1)
+ tkinter.Label(self.tk, text=header).grid(row=row, column=0)
+ tkinter.Label(self.tk, textvariable=label).grid(row=row, column=1)
row += 1
return row
@@ -279,13 +304,13 @@ def run(self):
def run_backtest(self):
def setup_bootstrap_conditions():
- self.pd_last_prices = pd.read_csv("ticks 10 mins - Jun 25 2014.csv")
+ self.pd_last_prices = pd.read_csv("C:\\Users\\jloss\\PyCharmProjects\\IB-Trading-Models-And-Backtester\\src\\ticks 10 mins - Jun 25 2014.csv")
self.pd_last_prices = self.pd_last_prices[-self.window_length:]
self.is_bootstrapped = True
setup_bootstrap_conditions()
- self.ibhft = bt.Backtester()
- self.ibhft.set_csv_file("ticks 10 mins - Jun 25 2014.csv")
+ self.ibhft = Backtester()
+ self.ibhft.set_csv_file("C:\\Users\\jloss\\PyCharmProjects\\IB-Trading-Models-And-Backtester\\src\\ticks 10 mins - Jun 25 2014.csv")
self.ibhft.start_data_stream(self.on_started
, self.on_tick
, STOCKS_TO_STREAM
@@ -293,4 +318,4 @@ def setup_bootstrap_conditions():
if __name__ == '__main__':
# TradingStrategy().run()
- TradingStrategy().run_backtest()
\ No newline at end of file
+ TradingStrategy().run_backtest()
diff --git a/src/ibDataTypes.py b/src/ibDataTypes.py
index 0cc7ad1..b086f89 100644
--- a/src/ibDataTypes.py
+++ b/src/ibDataTypes.py
@@ -1,7 +1,13 @@
-#######################################
+# --------------------------------------------------------
# Author: James Ma
# Email stuff here: jamesmawm@gmail.com
-#######################################
+#
+# Developed and updated by Joseph Loss on 6/19/2019
+# MS Financial Engineering
+# University of Illinois at Urbana-Champaign
+#
+# Inquiries: loss2@illinois.edu
+# --------------------------------------------------------
# https://www.interactivebrokers.com/en/software/api/apiguide/java/reqhistoricaldata.htm
# https://www.interactivebrokers.com/en/software/api/apiguide/tables/tick_types.htm
diff --git a/src/ibHFT.py b/src/ibHFT.py
index dd5b97a..f4eb390 100644
--- a/src/ibHFT.py
+++ b/src/ibHFT.py
@@ -1,13 +1,29 @@
-#######################################
+# --------------------------------------------------------
# Author: James Ma
# Email stuff here: jamesmawm@gmail.com
-#######################################
+#
+# Developed and updated by Joseph Loss on 6/19/2019
+# MS Financial Engineering
+# University of Illinois at Urbana-Champaign
+#
+# Inquiries: loss2@illinois.edu
+# --------------------------------------------------------
-import numpy as np
-from ib.opt import ibConnection, message
-from ib.opt import Connection
import time
from time import strftime
+from typing import Dict, Any
+import numpy as np
+
+from ib.opt import ibConnection
+from ib.opt import message
+from ib.ext import EWrapperMsgGenerator,EWrapper,TickType,EReader
+from ib.opt import Connection
+from ib.ext import EWrapper, EWrapperMsgGenerator as msg
+
+from ib.ext import EWrapper
+from ib import *
+
+
from StockTradable import *
from StockPosition import *
from StockOrder import *
@@ -15,6 +31,8 @@
class IbHFT:
+ positions_dict: Dict[Any, Any]
+
def __init__(self):
self.is_use_gateway = True
self.is_shutdown = False
@@ -147,21 +165,21 @@ def logger(self, msg):
self.process_error_message(msg)
else:
- print "logger: " , msg
+ print("logger: " , msg)
def process_error_message(self, msg):
if msg.errorCode == DataType.ERROR_CODE_MARKET_DATA_FARM_CONNECTED:
- print msg.errorMsg
+ print( msg.errorMsg)
elif msg.errorCode == DataType.ERROR_CODE_HISTORICAL_DATA_FARM_CONNECTED:
- print msg.errorMsg
+ print( msg.errorMsg)
elif msg.errorCode == DataType.ERROR_CODE_ORDER_CANCELED:
- print msg.errorMsg
+ print( msg.errorMsg)
else:
- print "Unhandled errcode: ", msg
+ print( "Unhandled errcode: ", msg)
def process_account_updates(self, msg):
# Do nothing for now
@@ -178,8 +196,8 @@ def process_portfolio_updates(self, msg):
self.positions_dict[stock_code].unrealized_pnl = msg.unrealizedPNL
return
- except Exception, e:
- print "process_portfolio_updates err:", e
+ except Exception as e:
+ print("process_portfolio_updates err:", e)
def get_positions(self):
return self.positions_dict
@@ -252,27 +270,29 @@ def tick_event(self, msg):
self.stock_ticks_dict[stock_code].volume = msg.size
else:
- print "Unhandle tick_event: ", msg
+ print("Unhandle tick_event: ", msg)
if self.on_tick_func is not None:
self.on_tick_func(self.stock_ticks_dict, stock_code, msg.field)
+
def register_event_handlers(self, ibconn, logger_func=None):
if logger_func is None:
logger_func = self.logger
ibconn.registerAll(logger_func)
ibconn.unregister(logger_func
- , message.tickSize
- , message.tickPrice
- , message.tickString
- , message.tickGeneric
- , message.tickOptionComputation
- , message.updateAccountTime
- , message.accountDownloadEnd
- , message.commissionReport)
-
- ibconn.register(self.tick_event, message.tickPrice, message.tickSize)
+ , EWrapperMsgGenerator.EWrapperMsgGenerator.tickSize
+ , EWrapperMsgGenerator.EWrapperMsgGenerator.tickPrice
+ , EWrapperMsgGenerator.EWrapperMsgGenerator.tickString
+ , EWrapperMsgGenerator.EWrapperMsgGenerator.tickGeneric
+ , EWrapperMsgGenerator.EWrapperMsgGenerator.tickOptionComputation
+ , EWrapperMsgGenerator.EWrapperMsgGenerator.updateAccountTime
+ , EWrapperMsgGenerator.EWrapperMsgGenerator.accountDownloadEnd
+ , EWrapperMsgGenerator.EWrapperMsgGenerator.commissionReport
+ )
+
+ ibconn.register(self.tick_event, EWrapperMsgGenerator.EWrapperMsgGenerator.tickPrice, EWrapperMsgGenerator.EWrapperMsgGenerator.tickSize)
def request_streaming_data(self, ibconn):
for i, stock_code in enumerate(self.stock_codes):
@@ -338,12 +358,12 @@ def start_historical_data_stream(self
while not self.is_shutdown:
time.sleep(1)
- except Exception, e:
- print "Err: ", e
- print "Disconnecting..."
+ except Exception as e:
+ print("Err: ", e)
+ print("Disconnecting...")
self.conn.disconnect()
time.sleep(1)
- print "Disconnected."
+ print("Disconnected.")
def assign_functions(self, func_a, func_b):
self.on_position_changed_func = func_a
@@ -367,15 +387,16 @@ def start_data_stream(self
self.request_account_updates(self.conn)
on_started_func()
- except Exception, e:
- print "Err: ", e
+ except Exception as e:
+ print("Err: ", e)
- print "Cancelling...",
+ print("Cancelling...", end = ' ')
self.cancel_market_data_request(self.conn)
- print "Disconnecting..."
+ print("Disconnecting...")
self.disconnect(self.conn)
time.sleep(1)
- print "Disconnected."
\ No newline at end of file
+ print("Disconnected.")
+
diff --git a/src/ibUtil.py b/src/ibUtil.py
index 2f887be..348216a 100644
--- a/src/ibUtil.py
+++ b/src/ibUtil.py
@@ -1,7 +1,13 @@
-#######################################
+# --------------------------------------------------------
# Author: James Ma
# Email stuff here: jamesmawm@gmail.com
-#######################################
+#
+# Developed and updated by Joseph Loss on 6/19/2019
+# MS Financial Engineering
+# University of Illinois at Urbana-Champaign
+#
+# Inquiries: loss2@illinois.edu
+# --------------------------------------------------------
from ib.ext.Contract import Contract
from ib.ext.Order import Order