Skip to main content

QTPyLib, Pythonic Algorithmic Trading

Python version PyPi version PyPi status Travis-CI build status Documentation Status Star this repo Follow me on twitter

QTPyLib (Quantitative Trading Python Library) is a simple, event-driven algorithmic trading library written in Python, that supports backtesting, as well as paper and live trading via Interactive Brokers.

I developed QTPyLib because I wanted for a simple, yet powerful, trading library that will let me focus on the trading logic itself and ignore everything else.

Full Documentation »

Changelog »


Features

  • A continuously-running Blotter that lets you capture market data even when your algos aren’t running.

  • Tick, Bar and Trade data is stored in MySQL for later analysis and backtesting.

  • Using pub/sub architecture using ØMQ (ZeroMQ) for communicating between the Algo and the Blotter allows for a single Blotter/multiple Algos running on the same machine.

  • Support for Order Book, Quote, Time, Tick or Volume based strategy resolutions.

  • Includes many common indicators that you can seamlessly use in your algorithm.

  • Market data events use asynchronous, non-blocking architecture.

  • Have orders delivered to your mobile via SMS (requires a Nexmo or Twilio account).

  • Full integration with TA-Lib via dedicated module (see documentation).

  • Ability to import any Python library (such as scikit-learn or TensorFlow) to use them in your algorithms.


Quickstart

There are 5 main components to QTPyLib:

  1. Blotter - handles market data retrieval and processing.

  2. Broker - sends and process orders/positions (abstracted layer).

  3. Algo - (sub-class of Broker) communicates with the Blotter to pass market data to your strategies, and process/positions orders via Broker.

  4. Reports - provides real-time monitoring of trades and open positions via Web App, as well as a simple REST API for trades, open positions, and market data.

  5. Lastly, Your Strategies, which are sub-classes of Algo, handle the trading logic/rules. This is where you’ll write most of your code.

1. Get Market Data

To get started, you need to first create a Blotter script:

# blotter.py
from qtpylib.blotter import Blotter

class MainBlotter(Blotter):
    pass # we just need the name

if __name__ == "__main__":
    blotter = MainBlotter()
    blotter.run()

Then, with IB TWS/GW running, run the Blotter from the command line:

$ python blotter.py

If your strategy needs order book / market depth data, add the --orderbook flag to the command:

$ python blotter.py --orderbook

2. Write your Algorithm

While the Blotter running in the background, write and execute your algorithm:

# strategy.py
from qtpylib.algo import Algo

class CrossOver(Algo):

    def on_start(self):
        pass

    def on_fill(self, instrument, order):
        pass

    def on_quote(self, instrument):
        pass

    def on_orderbook(self, instrument):
        pass

    def on_tick(self, instrument):
        pass

    def on_bar(self, instrument):
        # get instrument history
        bars = instrument.get_bars(window=100)

        # or get all instruments history
        # bars = self.bars[-20:]

        # skip first 20 days to get full windows
        if len(bars) < 20:
            return

        # compute averages using internal rolling_mean
        bars['short_ma'] = bars['close'].rolling_mean(window=10)
        bars['long_ma']  = bars['close'].rolling_mean(window=20)

        # get current position data
        positions = instrument.get_positions()

        # trading logic - entry signal
        if bars['short_ma'].crossed_above(bars['long_ma'])[-1]:
            if not instrument.pending_orders and positions["position"] == 0:

                # buy one contract
                instrument.buy(1)

                # record values for later analysis
                self.record(ma_cross=1)

        # trading logic - exit signal
        elif bars['short_ma'].crossed_below(bars['long_ma'])[-1]:
            if positions["position"] != 0:

                # exit / flatten position
                instrument.exit()

                # record values for later analysis
                self.record(ma_cross=-1)


if __name__ == "__main__":
    strategy = CrossOver(
        instruments = [ ("ES", "FUT", "GLOBEX", "USD", 201609, 0.0, "") ], # ib tuples
        resolution  = "1T", # Pandas resolution (use "K" for tick bars)
        tick_window = 20, # no. of ticks to keep
        bar_window  = 5, # no. of bars to keep
        preload     = "1D", # preload 1 day history when starting
        timezone    = "US/Central" # convert all ticks/bars to this timezone
    )
    strategy.run()

To run your algo in a live enviroment, from the command line, type:

$ python strategy.py --logpath ~/qtpy/

The resulting trades be saved in ~/qtpy/STRATEGY_YYYYMMDD.csv for later analysis.

3. Viewing Live Trades

While the Blotter running in the background, write the dashboard:

# dashboard.py
from qtpylib.reports import Reports

class Dashboard(Reports):
    pass # we just need the name

if __name__ == "__main__":
    dashboard = Dashboard(port = 5000)
    dashboard.run()

To run your dashboard, run it from the command line:

$ python dashboard.py

>>> Dashboard password is: a0f36d95a9
>>> Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

Now, point your browser to http://localhost:5000 and use the password generated to access your dashboard.


Installation

Install using pip:

$ pip install qtpylib --upgrade --no-cache-dir

Requirements

  • Python >=3.4

  • Pandas (tested to work with >=0.18.1)

  • Numpy (tested to work with >=1.11.1)

  • PyZMQ (tested to work with >=15.2.1)

  • PyMySQL (tested to work with >=0.7.6)

  • pytz (tested to work with >=2016.6.1)

  • dateutil (tested to work with >=2.5.1)

  • Nexmo-Python for SMS support (tested to work with >=1.2.0)

  • Twilio-Python for SMS support (tested to work with >=5.4.0)

  • Flask for the Dashboard (tested to work with >=0.11)

  • Requests (tested to work with >=2.10.0)

  • IbPy2 (tested to work with >=0.8.0)

  • ezIBpy (IbPy wrapper, tested to work with >=1.12.66)

  • Latest Interactive Brokers’ TWS or IB Gateway installed and running on the machine

  • MySQL Server installed and running with a database for QTPyLib


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

QTPyLib-1.5.83.tar.gz (118.3 kB view details)

Uploaded Source

File details

Details for the file QTPyLib-1.5.83.tar.gz.

File metadata

  • Download URL: QTPyLib-1.5.83.tar.gz
  • Upload date:
  • Size: 118.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: Python-urllib/3.7

File hashes

Hashes for QTPyLib-1.5.83.tar.gz
Algorithm Hash digest
SHA256 4a4a65f564a7f8fece3cabc2c783584cc158b8c6d356c29c2e0f8e1c4a1b339c
MD5 bae7fc73f923c12aec585849f14e3dbc
BLAKE2b-256 7186621ac3870dad934da7b53b23d4a25c2182bab8c538d3971b05b51213f735

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

1.5.83 This release

1 file

1.5.82

1 file

1.5.81

1 file

1.5.80

1 file

1.5.79

1 file

1.5.78

1 file

1.5.77

1 file

1.5.76

1 file

1.5.75

1 file

1.5.74

1 file

1.5.73

1 file

1.5.72

1 file

1.5.71

1 file

1.5.59

1 file

1.5.58

1 file

1.5.57

1 file

1.5.56

1 file

1.5.55

1 file

1.5.54

1 file

1.5.53

1 file

1.5.52

1 file

1.5.51

1 file

1.5.49

1 file

1.5.48

1 file

1.5.47

1 file

1.5.46

1 file

1.5.45

1 file

1.5.44

1 file

1.5.43

1 file

1.5.42

1 file

1.5.41

1 file

1.5.40

1 file

1.5.39

1 file

1.5.38

1 file

1.5.37

1 file

1.5.36

1 file

1.5.35

1 file

1.5.34

1 file

1.5.33

1 file

1.5.32

1 file

1.5.31

1 file

1.5.30

1 file

1.5.29

1 file

1.5.28

1 file

1.5.27

1 file

1.5.26

1 file

1.5.25

1 file

1.5.24

1 file

1.5.23

1 file

1.5.22

1 file

1.5.21

1 file

1.5.8

1 file

1.5.7

1 file

1.5.6

1 file

1.5.5

1 file

1.5.2

1 file

1.5.1

1 file

1.5.0

1 file

1.4.99

1 file

1.4.98

1 file

1.4.97

1 file

1.4.96

1 file

1.4.95

1 file

1.4.94

1 file

1.4.93

1 file

1.4.92

1 file

1.4.91

1 file

1.4.9

1 file

1.4.8

1 file

1.4.7

1 file

1.4.6

1 file

1.4.5

1 file

1.4.4

1 file

1.4.3

1 file

1.4.2

1 file

1.4.1

1 file

1.4.0

1 file

1.3.99

1 file

1.3.98

1 file

1.3.97

1 file

1.3.96

1 file

1.3.95

1 file

1.3.94

1 file

1.3.93

1 file

1.3.92

1 file

1.3.91

1 file

1.3.9

1 file

1.3.8

1 file

1.3.7

1 file

1.3.6

1 file

1.3.5

1 file

1.3.4

1 file

1.3.3

1 file

1.3.2

1 file

1.3.1

1 file

1.3.0

1 file

1.2.9

1 file

1.2.8

1 file

1.2.7

1 file

1.2.6

1 file

1.2.5

1 file

1.2.4

1 file

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page