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, tick_window=1, bar_window=100, timezone='UTC', preload=None, continuous=True, blotter=None, sms=[], log=None, backtest=False, start=None, end=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

resolution
: str

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

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 (using 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 MySQL server used by this Blotter (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

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_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

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 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 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