API Reference

Instrument API

The Instrument object is passed to the on_tick(), on_bar(), on_quote(), on_orderbook() and on_fill() methods in your strategy:

# startegy.py
def on_tick(self, instrument):
    instrument.MethodName(...)

def on_bar(self, instrument):
    instrument.MethodName(...)

def on_quote(self, instrument):
    instrument.MethodName(...)

def on_orderbook(self, instrument):
    instrument.MethodName(...)

def on_fill(self, instrument, order):
    instrument.MethodName(...)
class qtpylib.instrument.Instrument[source]

A string subclass that provides easy access to misc symbol-related methods and information.

get_bars(lookback=None, as_dict=False)[source]

Get bars for this instrument

Parameters:
lookback : int

Max number of bars to get (None = all available bars)

as_dict : bool

Return a dict or a pd.DataFrame object

Retruns:
bars : pd.DataFrame / dict

The bars for this instruments

get_bar()[source]

Shortcut to self.get_bars(lookback=1, as_dict=True)

get_ticks(lookback=None, as_dict=False)[source]

Get ticks for this instrument

Parameters:
lookback : int

Max number of ticks to get (None = all available ticks)

as_dict : bool

Return a dict or a pd.DataFrame object

Retruns:
ticks : pd.DataFrame / dict

The ticks for this instruments

get_tick()[source]

Shortcut to self.get_ticks(lookback=1, as_dict=True)

get_price()[source]

Shortcut to self.get_ticks(lookback=1, as_dict=True)[‘last’]

get_quote()[source]

Get last quote for this instrument

Retruns:
quote : dict

The quote for this instruments

get_orderbook()[source]

Get orderbook for the instrument

Retruns:
orderbook : dict

orderbook dict for the instrument

order(direction, quantity, **kwargs)[source]

Send an order for this instrument

Parameters:
direction : string

Order Type (BUY/SELL, EXIT/FLATTEN)

quantity : int

Order quantity

Optional:
limit_price : float

In case of a LIMIT order, this is the LIMIT PRICE

expiry : int

Cancel this order if not filled after n seconds (default 60 seconds)

order_type : string

Type of order: Market (default), LIMIT (default when limit_price is passed), MODIFY (required passing or orderId)

orderId : int

If modifying an order, the order id of the modified order

target : float

target (exit) price

initial_stop : float

price to set hard stop

stop_limit: bool

Flag to indicate if the stop should be STOP or STOP LIMIT (default False=STOP)

trail_stop_at : float

price at which to start trailing the stop

trail_stop_by : float

% of trailing stop distance from current price

fillorkill: bool

fill entire quantiry or none at all

iceberg: bool

is this an iceberg (hidden) order

tif: str

time in force (DAY, GTC, IOC, GTD). default is DAY

cancel_order(orderId)[source]

Cancels an order for this instrument

Parameters:
orderId : int

Order ID

market_order(direction, quantity, **kwargs)[source]

Shortcut for instrument.order(...) and accepts all of its optional parameters

Parameters:
direction : string

Order Type (BUY/SELL, EXIT/FLATTEN)

quantity : int

Order quantity

limit_order(direction, quantity, price, **kwargs)[source]

Shortcut for instrument.order(...) and accepts all of its optional parameters

Parameters:
direction : string

Order Type (BUY/SELL, EXIT/FLATTEN)

quantity : int

Order quantity

price : float

Limit price

buy(quantity, **kwargs)[source]

Shortcut for instrument.order("BUY", ...) and accepts all of its optional parameters

Parameters:
quantity : int

Order quantity

buy_market(quantity, **kwargs)[source]

Shortcut for instrument.order("BUY", ...) and accepts all of its optional parameters

Parameters:
quantity : int

Order quantity

buy_limit(quantity, price, **kwargs)[source]

Shortcut for instrument.order("BUY", ...) and accepts all of its optional parameters

Parameters:
quantity : int

Order quantity

price : float

Limit price

sell(quantity, **kwargs)[source]

Shortcut for instrument.order("SELL", ...) and accepts all of its optional parameters

Parameters:
quantity : int

Order quantity

sell_market(quantity, **kwargs)[source]

Shortcut for instrument.order("SELL", ...) and accepts all of its optional parameters

Parameters:
quantity : int

Order quantity

sell_limit(quantity, price, **kwargs)[source]

Shortcut for instrument.order("SELL", ...) and accepts all of its optional parameters

Parameters:
quantity : int

Order quantity

price : float

Limit price

exit()[source]

Shortcut for instrument.order("EXIT", ...) (accepts no parameters)

flatten()[source]

Shortcut for instrument.order("FLATTEN", ...) (accepts no parameters)

get_contract()[source]

Get contract object for this instrument

Retruns:
contract : Object

IB Contract object

get_contract_details()[source]

Get contract details for this instrument

Retruns:
contract_details : dict

IB Contract details

get_tickerId()[source]

Get contract’s tickerId for this instrument

Retruns:
tickerId : int

IB Contract’s tickerId

get_combo()[source]

Get instrument’s group if part of an instrument group

Retruns:
tickerId : int

IB Contract’s tickerId

get_positions(attr=None)[source]

Get the positions data for the instrument

Optional:
attr : string

Position attribute to get (optional attributes: symbol, position, avgCost, account)

Retruns:
positions : dict (positions) / float/str (attribute)

positions data for the instrument

get_portfolio()[source]

Get portfolio data for the instrument

Retruns:
portfolio : dict

portfolio data for the instrument

get_orders()[source]

Get orders for the instrument

Retruns:
orders : list

list of order data as dict

get_pending_orders()[source]

Get pending orders for the instrument

Retruns:
orders : list

list of pending order data as dict

get_active_order(order_type='STOP')[source]

Get artive order id for the instrument by order_type

Optional:
order_type : string

the type order to return: STOP (default), LIMIT, MARKET

Retruns:
order : object

IB Order object of instrument

get_trades()[source]

Get orderbook for the instrument

Retruns:
trades : pd.DataFrame

instrument’s trade log as DataFrame

get_symbol()[source]

Get symbol of this instrument

Retruns:
symbol : string

instrument’s symbol

modify_order(orderId, quantity=None, limit_price=None)[source]

Modify quantity and/or limit price of an active order for the instrument

Parameters:
orderId : int

the order id to modify

Optional:
quantity : int

the required quantity of the modified order

limit_price : int

the new limit price of the modified order

modify_order_group(orderId, entry=None, target=None, stop=None, quantity=None)[source]

Modify bracket order

Parameters:
orderId : int

the order id to modify

Optional:
entry: float

new entry limit price (for unfilled limit orders only)

target: float

new target limit price (for unfilled limit orders only)

stop: float

new stop limit price (for unfilled limit orders only)

quantity : int

the required quantity of the modified order

move_stoploss(stoploss)[source]

Modify stop order. Auto-discover orderId and quantity and invokes self.modify_order(...).

Parameters:
stoploss : float

the new stoploss limit price

get_margin_requirement()[source]

Get margin requirements for intrument (futures only)

Retruns:
margin : dict

margin requirements for instrument (all values are None for non-futures instruments)

get_max_contracts_allowed(overnight=True)[source]

Get maximum contracts allowed to trade baed on required margin per contract and current account balance (futures only)

Parameters:
overnight : bool

Calculate based on Overnight margin (set to False to use Intraday margin req.)

Retruns:
contracts : int

maximum contracts allowed to trade (returns None for non-futures)

get_margin_max_contracts(overnight=True)[source]

Deprecated (renamed to get_max_contracts_allowed)

get_ticksize()[source]

Get instrument ticksize

Retruns:
ticksize : int

Min. tick size

pnl_in_range(min_pnl, max_pnl)[source]

Check if instrument pnl is within given range

Parameters:
min_pnl : flaot

minimum session pnl (in USD / IB currency)

max_pnl : flaot

maximum session pnl (in USD / IB currency)

Retruns:
status : bool

if pnl is within range

log_signal(signal)[source]

Log Signal for instrument

Parameters:
signal : integer

signal identifier (1, 0, -1)

bars

(Property) Shortcut to self.get_bars()

bar

(Property) Shortcut to self.get_bar()

ticks

(Property) Shortcut to self.get_ticks()

tick

(Property) Shortcut to self.get_tick()

price

(Property) Shortcut to self.get_price()

quote

(Property) Shortcut to self.get_quote()

orderbook

(Property) Shortcut to self.get_orderbook()

symbol

(Property) Shortcut to self.get_symbol()

contract

(Property) Shortcut to self.get_contract()

contract_details

(Property) Shortcut to self.get_contract_details()

tickerId

(Property) Shortcut to self.get_tickerId()

combo

(Property) Shortcut to self.get_combo()

positions

(Property) Shortcut to self.get_positions()

position

(Property) Shortcut to self.get_positions(position)

portfolio

(Property) Shortcut to self.get_portfolio()

orders

(Property) Shortcut to self.get_orders()

pending_orders

(Property) Shortcut to self.get_pending_orders()

trades

(Property) Shortcut to self.get_trades()

margin_requirement

(Property) Shortcut to self.get_margin_requirement()

margin_max_contracts

Deprecated (renamed to max_contracts_allowed)

max_contracts_allowed

(Property) Shortcut to self.get_max_contracts_allowed()

ticksize

(Property) Shortcut to self.get_ticksize()


Algo API

Algo is a Sub-Class of Broker and the Parent Class for your strategies. Aside from algo.run(...), all the other methods should be called from within your strategy via self.MethodName(...).

For example:

# startegy.py

# record something
self.record(key=value)

# send custom text
self.sms("message text")

# get instrument object
instrument = self.get_instrument("SYMBOL")
class qtpylib.algo.Algo(instruments, resolution='1T', tick_window=1, bar_window=100, timezone='UTC', preload=None, continuous=True, blotter=None, sms=None, log=None, backtest=False, start=None, end=None, data=None, output=None, ibclient=998, ibport=4001, ibserver='localhost', **kwargs)[source]

Algo class initilizer (sub-class of Broker)

Parameters:
instruments : list

List of IB contract tuples. Default is empty list

resolution : str

Desired bar resolution (using pandas resolution: 1T, 1H, etc). Use K for tick bars. Default is 1T (1min)

tick_window : int

Length of tick lookback window to keep. Defaults to 1

bar_window : int

Length of bar lookback window to keep. Defaults to 100

timezone : str

Convert IB timestamps to this timezone (eg. US/Central). Defaults to UTC

preload : str

Preload history when starting algo (Pandas resolution: 1H, 1D, etc) Use K for tick bars.

continuous : bool

Tells preloader to construct continuous Futures contracts (default is True)

blotter : str

Log trades to this Blotter’s MySQL (default is “auto detect”)

sms: set

List of numbers to text orders (default: None)

log: str

Path to store trade data (default: None)

backtest: bool

Whether to operate in Backtest mode (default: False)

start: str

Backtest start date (YYYY-MM-DD [HH:MM:SS[.MS]). Default is None

end: str

Backtest end date (YYYY-MM-DD [HH:MM:SS[.MS]). Default is None

data : str

Path to the directory with QTPyLib-compatible CSV files (Backtest)

output: str

Path to save the recorded data (default: None)

ibport: int

IB TWS/GW Port to use (default: 4001)

ibclient: int

IB TWS/GW Client ID (default: 998)

ibserver: str

IB TWS/GW Server hostname (default: localhost)

run()[source]

Starts the algo

Connects to the Blotter, processes market data and passes tick data to the on_tick function and bar data to the on_bar methods.

on_start()[source]

Invoked once when algo starts. Used for when the strategy needs to initialize parameters upon starting.

on_quote(instrument)[source]

Invoked on every quote captured for the selected instrument. This is where you’ll write your strategy logic for quote events.

Parameters:
symbol : string

Instruments Object

on_tick(instrument)[source]

Invoked on every tick captured for the selected instrument. This is where you’ll write your strategy logic for tick events.

Parameters:
symbol : string

Instruments Object

on_bar(instrument)[source]

Invoked on every tick captured for the selected instrument. This is where you’ll write your strategy logic for tick events.

Parameters:
instrument : object

Instruments Object

on_fill(instrument, order)[source]

Invoked on every order fill for the selected instrument. This is where you’ll write your strategy logic for fill events.

Parameters:
instrument : object

Instruments Object

order : object

Filled order data

get_history(symbols, start, end=None, resolution='1T', tz='UTC')[source]

Get historical market data. Connects to Blotter and gets historical data from storage

Parameters:
symbols : list

List of symbols to fetch history for

start : datetime / string

History time period start date datetime or YYYY-MM-DD[ HH:MM[:SS]] string)

Optional:
end : datetime / string

History time period end date (datetime or YYYY-MM-DD[ HH:MM[:SS]] string)

resolution : string

History resoluton (Pandas resample, defaults to 1T/1min)

tz : string

History timezone (defaults to UTC)

Returns:
history : pd.DataFrame

Pandas DataFrame object with historical data for all symbols

order(signal, symbol, quantity=0, **kwargs)[source]

Send an order for the selected instrument

Parameters:
direction : string

Order Type (BUY/SELL, EXIT/FLATTEN)

symbol : string

instrument symbol

quantity : int

Order quantiry

Optional:
limit_price : float

In case of a LIMIT order, this is the LIMIT PRICE

expiry : int

Cancel this order if not filled after n seconds (default 60 seconds)

order_type : string

Type of order: Market (default), LIMIT (default when limit_price is passed), MODIFY (required passing or orderId)

orderId : int

If modifying an order, the order id of the modified order

target : float

Target (exit) price

initial_stop : float

Price to set hard stop

stop_limit: bool

Flag to indicate if the stop should be STOP or STOP LIMIT. Default is False (STOP)

trail_stop_at : float

Price at which to start trailing the stop

trail_stop_type : string

Type of traiing stop offset (amount, percent). Default is percent

trail_stop_by : float

Offset of trailing stop distance from current price

fillorkill: bool

Fill entire quantiry or none at all

iceberg: bool

Is this an iceberg (hidden) order

tif: str

Time in force (DAY, GTC, IOC, GTD). default is DAY

cancel_order(orderId)[source]

Cancels a un-filled order

Parameters:
orderId : int
Order ID
record(*args, **kwargs)[source]

Records data for later analysis. Values will be logged to the file specified via --output [file] (along with bar data) as csv/pickle/h5 file.

Call from within your strategy: self.record(key=value)

Parameters:
** kwargs : mixed

The names and values to record

sms(text)[source]

Sends an SMS message. Relies on properly setting up an SMS provider (refer to the SMS section of the documentation for more information about this)

Call from within your strategy: self.sms("message text")

Parameters:
text : string

The body of the SMS message to send

get_instrument(symbol)

A string subclass that provides easy access to misc symbol-related methods and information using shorthand. Refer to the Instruments API for available methods and properties

Call from within your strategy: instrument = self.get_instrument("SYMBOL")

Parameters:
symbol : string

instrument symbol


Blotter API

class qtpylib.blotter.Blotter(name=None, symbols='symbols.csv', ibport=4001, ibclient=999, ibserver='localhost', dbhost='localhost', dbport='3306', dbname='qtpy', dbuser='root', dbpass='', dbskip=False, orderbook=False, zmqport='12345', zmqtopic=None, **kwargs)[source]

Broker class initilizer

Optional:
name : string

name of the blotter (used by other modules)

symbols : str

IB contracts CSV database (default: ./symbols.csv)

ibport : int

TWS/GW Port to use (default: 4001)

ibclient : int

TWS/GW Client ID (default: 999)

ibserver : str

IB TWS/GW Server hostname (default: localhost)

zmqport : str

ZeroMQ Port to use (default: 12345)

zmqtopic : str

ZeroMQ string to use (default: _qtpylib_BLOTTERNAME_)

orderbook : str

Get Order Book (Market Depth) data (default: False)

dbhost : str

MySQL server hostname (default: localhost)

dbport : str

MySQL server port (default: 3306)

dbname : str

MySQL server database (default: qpy)

dbuser : str

MySQL server username (default: root)

dbpass : str

MySQL server password (default: none)

dbskip : str

Skip MySQL logging (default: False)

run()[source]

Starts the blotter

Connects to the TWS/GW, processes and logs market data, and broadcast it over TCP via ZeroMQ (which algo subscribe to)

qtpylib.blotter.get_symbol_id(...)[source]

Retrives symbol’s ID from the Database or create it if it doesn’t exist

Parameters:
symbol : str

Instrument symbol

dbconn : object

Database connection to be used

dbcurr : object

Database cursor to be used

Optional:
ibConn : object

ezIBpy object (used for determining futures/options expiration)

Returns:
symbol_id : int

Symbol ID

qtpylib.blotter.load_blotter_args(...)[source]

Load running blotter’s settings (used by clients)

Parameters:
blotter_name : str

Running Blotter’s name (defaults to “auto-detect”)

logger : object

Logger to be use (defaults to Blotter’s)

Returns:
args : dict

Running Blotter’s arguments


Broker API

Broker is the Parent Class of Algo, which, in turn, is the Parent Class for your strategies. All the following methods are available from within your strategy via self.MethodName(...)`.

class qtpylib.broker.Broker(instruments, ibclient=998, ibport=4001, ibserver='localhost')[source]

Broker class initilizer (abstracted, parent class of Algo)

Parameters:
instruments : list

List of IB contract tuples

ibclient : int

IB TWS/GW Port to use (default: 4001)

ibport : int

IB TWS/GW Client ID (default: 998)

ibserver : string

IB TWS/GW Server hostname (default: localhost)

add_instruments(*instruments)[source]

add instruments after initialization

register_combo(parent, legs)[source]

add contracts to groups

get_combo(symbol)[source]

get group by child symbol

get_instrument(symbol)[source]

A string subclass that provides easy access to misc symbol-related methods and information using shorthand. Refer to the Instruments API for available methods and properties

Call from within your strategy: instrument = self.get_instrument("SYMBOL")

Parameters:
symbol : string

instrument symbol


Reports API

class qtpylib.reports.Reports(blotter=None, port=5000, host='0.0.0.0', password=None, **kwargs)[source]

Reports class initilizer

Optional:
blotter : str

Log trades to MySQL server used by this Blotter (default is “auto detect”)

port : int

HTTP port to use (default: 5000)

host : string

Host to bind the http process to (defaults 0.0.0.0)

password : string

Password for logging in to the web app (auto-generated by default). Use “” for no password.

run()[source]

Starts the reporting module

Makes the dashboard web app available via localhost:port, and exposes a REST API for trade information, open positions and market data.


Workflow API

qtpylib.workflow.get_data_ib(...)[source]

Downloads historical data from Interactive Brokers

Parameters:
instrument : mixed

IB contract tuple / string (same as that given to strategy)

start : str

Backtest start date (YYYY-MM-DD [HH:MM:SS[.MS])

Optional:
resolution : str

1/5/15/30 secs, 1/2/3/5/15/30 min (default 1min), 1 hour, 1 day

blotter : str

Store MySQL server used by this Blotter (default is “auto detect”)

output_path : str

Path to where the resulting CSV should be saved (optional)

Returns:
data : pd.DataFrame

Pandas DataFrame in a QTPyLib-compatible format and timezone

qtpylib.workflow.prepare_data(...)[source]

Converts given DataFrame to a QTPyLib-compatible format and timezone

Parameters:
instrument : mixed

IB contract tuple / string (same as that given to strategy)

data : pd.DataFrame

Pandas DataDrame with that instrument’s market data

output_path : str

Path to where the resulting CSV should be saved (optional)

index : pd.Series

Pandas Series that will be used for df’s index (optioanl)

colsmap : dict

Dict for mapping df’s columns to those used by QTPyLib (default assumes same naming convention as QTPyLib’s)

kind : str

Is this BAR or TICK data

resample : str

Pandas resolution (defaults to 1min/1T)

Returns:
data : pd.DataFrame

Pandas DataFrame in a QTPyLib-compatible format and timezone

Note

The colsmap parameter structure expect a dict that maps QTPyLib’s columns names with the one used by your DataFrame.

The dict should be in the following structure: "qtpylib_column_name": "your_column_name", which any missing colsmap key is assumed to use the same name as QTPyLib’s. For example:

from qtpylib import workflow

newdf = workflow.prepare_data("AAPL", data=df,
    colsmap={'open':'O', 'high':'H', 'low':'L', 'close':'C', 'volume':'V'})
  • QTPyLib’s columns are:
    open, high, low, close, volume
  • QTPyLib’s Options’ data also include:
    opt_price, opt_underlying, opt_dividend, opt_volume, opt_iv, opt_oi, opt_delta, opt_gamma, opt_vega
qtpylib.workflow.store_data(...)[source]

Store QTPyLib-compatible csv files in Blotter’s MySQL. TWS/GW data are required for determining futures/options expiration

Parameters:
df : dict

Tick/Bar data

Optional:
blotter : str

Store MySQL server used by this Blotter (default is “auto detect”)

kind : str

Is this BAR or TICK data