IBridgePy documentation

Rent-a-Coder

Contents

API documentation

RUN_ME.py: the main entry of IBridgePy

runMode

There are a few options for runMode:

run_regular (default value): In this mode, handle_data runs every second,  not considering any market open and close time or holidays. before_trading_start ( the function provided in Quantopian) is ignored.

run_like_quantopian: In this mode, the function of handle_data runs every minute from 9:30:00 AM to 3:59:00 PM US eastern time, as same as the same function in Quantopian does. The function of before_trading_start runs at 9:20:00 AM U.S. eastern time every trading day if it is defined by user.

logLevel

logLevel = ‘ERROR’ : You will only see error messages from IB server.

logLevel = ‘INFO’ : You will see error messages plus info messages. This is the default value.

logLevel = ‘DEBUG’ : Debug messages will be shown upon info messages. This is the best way to debug your code.

logLevel = ‘NOTSET’. You will see all IBridgePy messages to understand how your code and IBridgePy are executed. Maybe it has too much information for beginners.

initialize — similar as initialize at Quantopian

initialize(context)

initialize(context) is a required setup method for initializing state or other bookkeeping. This method is called only once at the beginning of your algorithm. context is an augmented Python dictionary used for maintaining state during your backtest or live trading session. context should be used instead of global variables in the algorithm. Properties can be accessed using dot notation (context.some_property).


handle_data — similar as handle_data at Quantopian

handle_data(context, data)

handle_data(context, data) is an required method that is called every second or every minute, which is specified in the RUN_ME.py . context is the augmented Python dictionary that is defined in initialize (context) so that you may use context.some_property in the following part of handle_data function.

before_trading_start — similar as before_trading_start at Quantopian

before_trading_start(context, data)

before_trading_start is optional. It will be called daily prior to the open of market if IBridgePy is in the mode of run_like_quantopian. The time when before_trading_start is called can be configured by users.

Data method — similar as Data method at Quantopian

The data object is passed to handle_data and before_trading_start.

data.current — similar as data.current at Quantopian

data.current(security, fields)

Returns the real time value of the given securities for the given fields.

security: Security object, created by either of symbol( ) or symbols( ) or superSymbols( )

fields: string or iterable of strings. Valid values are ‘ask_price’, ‘bid_price’, ‘ask_size’, ‘bid_size’, ‘price’, ‘last_traded’, ‘open’, ‘high’, ‘low’, ‘close’ and ‘volume’.

Returns

If a single security and a single field are passed in, a scalar value is returned.

If a single security and a list of fields are passed in, a pandas Series is returned whose indices are the fields, and whose values are scalar values for this asset for each field.

If a list of securities and a single field are passed in, a pandas Series is returned whose indices are the securities, and whose values are scalar values for each asset for the given field.

If a list of securities and a list of fields are passed in, a pandas DataFrame is returned, indexed by securities. The columns are the requested fields, filled with the scalar values for each security for each field.


data.history — similar as data.history at Quantopian

data.history(security, fields, bar_count, frequency)

Returns a historical data from IB server. IB’s historical data is adjusted for splits, but not dividends

security: Security object, created by either of symbol( ) or symbols( ) or superSymbols( )

string fields: string or iterable of strings. Valid values are ‘price’, ‘open’, ‘high’, ‘low’, ‘close’ and ‘volume’

int bar_count: number of bars

string frequency: ‘1m’ for minutely data or ‘1d’ for daily date

Returns

If single security and field are passed in, the returned Series is indexed by date.

If multiple securities and single field are passed in, the returned DataFrame is indexed by date, and has securities as columns.

If a single securities and multiple fields are passed in, the returned DataFrame is indexed by date, and has fields as columns.

If multiple securities and multiple fields are passed in, the returned Panel is indexed by field, has date as the major axis, and securities as the minor axis.


order — similar as order at Quantopian

order(security, amount, style=MarketOrder ( ) , outsideRth=False)

Place order to IB server. The default order type is market order. User needs to consider the margin requirement when placing market orders.

security: Security object, created by either of symbol( ) or symbols( ) or superSymbols( )

int amount: the number of shares of the order. Positive means to buy the security and negative means to sell the security. For example, order(symbol(‘SPY’), 100) means to buy 100 shares of SPY and order(symbol(‘SPY’), -100) means to sell 100 shares of SPY.

style: The style of the order to be placed. The default style is market order.

IBridgePy supports the following order types:

  • market order: order(security, amount)
  • limit order: order(security, amount, LimitOrder(limitPrice), the default time-in-force is “all open orders are cancelled at the end of the day”. If “Good-Til-Canceled” is needed, it can be specified as LimitOrder(limitPrice, tif = ‘GTC’)
  • stop order: order(security, amount, StopOrder(stopPrice’), the default time-in-force is “all open orders are cancelled at the end of the day”. If “Good-Til-Canceled” is needed, it can be specified as StopOrder(stopPrice, tif = ‘GTC’)
  • trailing stop limit order: order(security, amount, TrailStopLimitOrder(stop_price, trailing_amount, limit_offset)). More details about trailing stop limit order is here https://www.interactivebrokers.com/en/index.php?f=606
  • limitPrice and stopPrice must follow the security’s minimum tick size requirement. A convenient function roundToMinTick is provided.

bool outsideRth: True = allow limit/stop order to be executed outside the regular trading hours. Some securities do not have a pre-defined trading hours, for example, Forex. Users should pay more attention on if the order should be allowed to executed outside the regular trading hours. IBridgePy does not check the validity.

Return: int orderId

order_target — similar as order_target at Quantopian

order_target (security, amount, style = MarketOrder ( ) )

Places an order to adjust a position to a target number of shares. User needs to consider the margin requirement when placing market orders.

For example, the current position of symbol(‘SPY’) is 100 shares. After execute order_target(symbol(‘SPY’), 200), another 100 share of SPY will be ordered to reach 200 shares of SPY on hand.

order_percent — similar as order_percent at Quantopian

order_percent (security, amount, style = MarketOrder ( ) )

Places an order in the specified security corresponding to the given percent of the current portfolio value, which is the sum of the positions value and ending cash balance. Placing a negative percent order will result in selling the given percent of the current portfolio value. Orders are always truncated to whole shares or contracts. Percent must be expressed as a decimal (0.50 means 50%), the range of [-1.0, 1.0]. User needs to consider the margin requirement when placing market orders.

order_percent(symbol(‘AAPL’), 0.5) will order AAPL shares worth 50% of current portfolio value. If AAPL is $100/share and the portfolio value is $2000, this buys 10 shares (discarding slippage and transaction cost).

order_target_percent — similar as order_target_percent at Quantopian

order_target_percent (security, percent, style = MarketOrder ( ) )

User needs to consider the margin requirement when placing market orders. 

order_value — similar as order_value at Quantopian

order_value (security, value, style = MarketOrder ( ) )

User needs to consider the margin requirement when placing market orders.

order_target_value — similar as order_target_value at Quantopian

order_target_value (security, value, style = MarketOrder ( ) )

User needs to consider the margin requirement when placing market orders.

cancel_order — similar as cancel_order at Quantopian

cancel_order(order)

To cancel a specific order that has not been executed.

Order can be either orderId or an instance of Order class.

Return None.*

* IB server will send a message “errorCode = 202, error message: Order Canceled – reason:”, which can be used to monitor the status of cancel_order

* An order placed by a clientId cannot be canceled by other clientId

get_open_orders — similar as get_open_orders at Quantopian

get_open_orders(security=None)

If security is None, all open orders will be returned in a dictionary keyed by securities. The dictionary contains a list of order for each orderId. If security is specified, a list of order for the security will be returned.

security: Security object, created by either of symbol( ) or symbols( ) or superSymbols( )

get_order  — similar as get_order at Quantopian

get_order(order)

Returns the specified order. The order object is discarded at the end of handle_data.

get_datetime — similar as get_datetime at Quantopian

get_datetime()

Returns the current system time in the format of python datetime on the IB server side. The time is localized based on the value of showTimeZone in the RUN_ME.py. To specify a timezone, please refer to the python module of pytz. Commonly used timezones are ‘US/Eastern’ and ‘US/Pacific’. The exhaust list of timezone is here.

For example, to show a datetime using timezone of US/Pacific, the following line can be added in RUN_ME.py

showTimeZone=’US/Pacific’

symbol — similar as symbol at Quantopian

symbol('symbol1')

The method to create a Security object.

Input: string

The format for stocks and ETFs is Stock(STK), Symbol name, base currency. For example,  ‘STK, AAPL, USD’ stands for the stock of Apple Inc, ‘STK, GOOG, USD’ is the stock of  Alphabet Inc. As a shortcut, the input can be the ticker of the company, such as symbol(‘AAPL”) or symbol(‘GOOG’).
The format for FOREX is CASH, base currency, quote currency. For example,  ‘CASH, EUR, USD’ or ‘CASH, USD, JPY’

Return: a Security object.

symbols — similar as symbols at Quantopian

symbols('symbol1','symbol2', 'symbol3',...)

Create a list of security objects. All of the symbols should follow the pre-determined format.

schedule_function– similar as schedule_function at Quantopian

schedule_function(func=myfunc, date_rule=date_rule, time_rule=time_rule, calendar=calendar)

The following explanation of the function is copied from www.quantopian.com and some of contents are modified to explain the function in IBridgePy. This function can only be used when runMode = ‘run_like_quantopian’.

Automatically run a function on a predetermined schedule. Can only be called from inside initialize.

func: The name of the function to run. This function must accept context and data as parameters, which will be the same as those passed to handle_data.

date_rule: Specifies the date portion of the schedule. This can be every day, week, or month and has an offset parameter to indicate days from the first or last of the month. The default is daily, and the default offset is 0 days. In other words, if no date rule is specified, the function will run every day.

The valid values for date_rule are:

  • date_rules.every_day()
  • date_rules.week_start(days_offset=0)
  • date_rules.week_end(days_offset=0)
  • date_rules.month_start(days_offset=0)
  • date_rules.month_end(days_offset=0)

time_rule: Specifies the time portion of the schedule. This can be set as market_open or market_close and has an offset parameter to indicate how many hours or minutes from the market open or close. The default is market open, and 1 minute before close.

The valid values for time_rule are:

  • time_rules.market_open(hours=0, minutes=1)
  • time_rules.market_close(hours=0, minutes=1)

calendar: Specifies the calendar on which the time rules will be based. The US Equities calendar day opens at 9:30AM and closes at 4:00PM (ET) while the US Future calendar day opens at 6:30AM and closes at 5:00PM (ET).

The valid values for calendar are:

  • calendars.US_EQUITIES
  • calendars.US_FUTURES

record — similar as record at Quantopian

record(‘variable1’, value1, ‘variable2’, value2, …)

Records the given strings and values.

Returns:
The data will be saved at IBridgePy/Log/userLog_YY_MM_DD_HH_MM_SS.txt

superSymbol

superSymbol(self, secType=None, symbol=None, currency=’USD’, exchange=’ ‘, primaryExchange=’ ‘, expiry=’ ‘, strike=0.0, right=’ ‘, multiplier=’ ‘, includeExpired=False)

Create a security object by clearly defining every details. It can be used to define any securities/commodities that are available at IB.

string secType:  STK, OPT, FUT, IND, CASH; (FOP, BAG, NEWS upon request)

Security symbol: Symbol of securities that are defined by IB

string currency: Check IB’s definition, ‘USD’,’GBP’, etc.

string exchange: Designate the trading exchange. Default exchange is ‘SMART’.

string primaryExchange: The primary exchange of the securities

string expiry: Used for futures and options.

float strike: Strike price for futures and options.

string right: “C’ for Call, “P” for Put.

string multiplier: Required for futures and options

bool includeExpired: Set it to True if you are working on expired futures/options and require historical data

For example:

Stock of Apple Inc.: superSymbol(secType=’STK’, symbol=’AAPL’, currency=’USD’, exchange=’SMART’, primaryExchange=’NASDAQ)

FOREX of EUR/USD: superSymbol(secType=’CASH’, symbol=’EUR’, currency=’USD’)

Index of VIX : superSymbol(secType=’IND’, symbol=’VIX’, currency=’USD’)

Futures of E-mini SP500 expiry of March 2015: superSymbol(secType=’FUT’, symbol=’ES’, currency=’USD’, expiry=’201503′, exchange=’GLOBEX’)

Option of  E-mini SP500, expiry of December 6th 2016, in US dollars, strike price of 2210, PUT, multiplier of 100: superSymbol(secType=’OPT’, symbol=’ES’, currency=’USD’, exchange=’GLOBEX’, primaryExchange=’GLOBEX’, expiry=’20161206′, strike=2210, right=’C’, multiplier=’100′, includeExpired=True)

show_real_time_price

show_real_time_price(security, version)

The method is to request real time quotes of the specified security from IB’s server. The error message will come back if the user has not subscribed the real time quotes of the requested security in the IB account. The first time when the function is called, IBridgePy requests the real time quotes from the IB server and the real time prices will come back automatically until the request is cancelled. In case you don’t want to wait to initiate the real time price request to IB server in handle_data ( ), you can call show_real_time_price ( ) in initialize ( ).

security: A security object, created by the function of symbol(‘symbol’)
version:

  • bid_price: return the latest bid price of the security
  • ask_price: return the latest ask price of the security
  • last_price: return the last price of the security if it is applicable to the security
  • bid_size: return the latest bid size
  • ask_size: return the latest ask size
  • volume: return the latest volume
  • high: return the latest daily high
  • low: return the latest daily low

Return: price in float.

Rent-a-Coder

Context object

The context object passed in handle_data(context, data) contains a portfolio object that contains information about account values, positions, open orders and other critical information.

context.portfolio.positions

The position object represents a current open position, and is contained inside the positions dictionary. For example, if you had an open AAPL position, you’d access it using context.portfolio.positions[symbol(‘AAPL’)]. Please email IBridgePy@gmail.com if you really need this feature to run within initialize( ).

The position object has the following properties:

int amount: Whole number of shares in this position.

float cost_basis: The volume-weighted average price paid (price and commission) per share in this position.

For example, to get the cost basis of a position of AAPL, the code looks like:

cost_basis = context.portfolio.positions[symbol(‘AAPL’)].cost_basis

 

context.portfolio.portfolio_value

context.portfolio.positions_value

context.portfolio.cash

The following example is to print the portfolio_value, positions_value and cash value in the account with system time printed as well.

def initialize(context):
    pass

def handle_data(context, data):
    print (get_datetime()) 
    print (context.portfolio.portfolio_value)
    print (context.portfolio.positions_value)
    print (context.portfolio.cash)
    end()

Order status

The possible values include:

  • PendingSubmit: The order is transmitted but the confirmation have not been received.
  • PendingCancel: A request to cancel the order is sent but the confirmation have not been received.
  • PreSubmitted: A simulated order type has been accepted by the IB system and that this order has yet to be elected.
  • Submitted: The order has been accepted.
  • Cancelled: The order has been canceled by the IB system.
  • Filled: The order has been completely filled.
  • Inactive: The order is inactive due to system, exchange or other issues

request_historical_data

request_historical_data(security, barSize, goBack, endTime=’default’, whatToShow=None, useRTH=1, formatDate=2, waitForFeedbackinSeconds=30)

To obtain historical data from IB. IB’s historical data is adjusted for splits, but not dividends

Input:

Security security: use symbol( ) or symbols( ) or superSymbol( ) to define security

string barSize: 1 sec, 5 secs, 15 secs, 30 secs, 1 min, 2 mins, 3 mins, 5 mins, 15 mins, 30 mins, 1 hour, 1 day

string goBack: Valid values include any integer followed by a space and then S (seconds), D (days), W (week), M(month) or Y(year).

For example, ’10 D’ stands for 10 days and ‘2 Y’ stands for 2 years.

The goBack value should be thoughtfully chosen. Otherwise, you will see the error message like “Historical data requests for duration longer than 365 days must be made in years”.

datetime endTime:  Defines a query end date and time at any point. Use python datetime object.

string whatToShow : values could be “TRADES”, “MIDPOINT”, “BID”, “ASK”, “BID_ASK” and etc. Please note that the historical data IB provide is always adjusted for split. If you need historical data to be adjusted for dividends as well, you need to set whatToShow = “ADJUSTED_LAST”

int useRTH:  1 = retrieve data generated only within Regular Trading Hours (RTH); 0 = all data is returned even where the market in question was outside of its regular trading hours.

int formatDate: 1 – dates applying to bars returned in the format: yyyymmdd{space}{space}hh:mm:dd; 2 – dates are returned as a long integer specifying the number of seconds since 1/1/1970 GMT.

int waitForFeedbackinSeconds: The algorithm will be terminated if IBridgePy has not received the expected results from IB server after x seconds.

Output:

A python pandas dataFrame will be returned. columns are “open”, “high”, “low”, “close” and “volume” and index is python datetime or date.

create_order

create_order(action, amount, security, orderDetails, ocaGroup=None, ocaType=None, transmit=None, parentId=None)

User create_order to clear define all kinds orders that IB supports using critical parameters.

action: “BUY” or “SELL”

amount: number of shares, must > 0

security: a security object that is created by symbol ( ) , symbols ( ) or superSymbol ( )

orderDetails: an instance created by MarketOrder ( ) or StopOrder ( ) or LimitOrder ( ) or TrailStopLimitOrder ( ) or any other order types supported by IB.

ocaGroup:  OCA stands for One Cancel All. Users should put a unique string.

ocaType:

  • 1 = Cancel all remaining orders with block
  • 2 = Remaining orders are proportionately reduced in size with block
  • 3 = Remaining orders are proportionately reduced in size with no bloc

transmit: Specifies whether the order will be transmitted. If set to false, the order will be created at TWS/Gateway but will not be sent.

parentId: the order ID of the parent order, used for bracket and auto trailing stop orders.

An example:

The following code will create a bracket order with three legs. Execution of any leg will cancel the other two legs. A limit order to purchase 2 share of SPY at $239.10,  a limit order at $240.50 and a stop order at $238.50. An unique string (“test”) at ocaGroup is to make sure these three orders will be set as One Cancel All.

leg0=create_order('BUY', 2, symbol('SPY'), LimitOrder(239.10), ocaGroup='test')
leg1=create_order('SELL', 2, symbol('SPY'), LimitOrder(240.50), ocaGroup='test')
leg2=create_order('SELL', 2, symbol('SPY'), StopOrder(238.50), ocaGroup='test')

place_combination_orders

place_combination_orders(legList)

legList: a list containing the legs that are created by create_order ( )

Return: a list of orderIds corresponding to the legs.

place_combination_orders([leg0,leg1,leg2])

cancel_all_orders

cancel_all_orders( )

Cancel all orders that are not executed yet.

Return: None

close_all_positions

close_all_positions(orderStatusMonitor=True)

Close all positions in the account.

bool orderStatusMonitor: use the function of orderStatusMonitor to follow up on the order status if True.

Return: None

count_positions

count_positions(security)

Count the number of shares of a security that the account is currently holding

Security security: use symbol( ) or symbols( ) or superSymbol( ) to define security

Return: int

count_open_orders

count_open_orders(security)

Count the number of shares of a security that the account is holding as an open order

Security security: use symbol( ) or symbols( ) or superSymbol( ) to define security

Return: int

order_status_monitor

order_status_monitor(orderId, target_status, waitingTimeInSeconds=30)

Keep monitoring the order status by orderId. Terminate the code if the target_status is not received with a period of time in seconds. As a critical warning to users, the termination of the code will inform the users to investigate the root cause of unexpected order statuses.

int orderId : order ID returned from order functions.

string or a list of string target_status : the expected order status or statuses. For example, [‘Filled’, ‘Submitted’]. Either of order statuses will deemed as a successful sign of the order placement.

int waitingTimeInSeconds : user can specify how long the monitor will keep waiting for the responses from IB server about an order.

Return Boolean. If the expected order status/statuses are not received with a period of time, the code will terminate. Otherwise, return True.

get_order_status

get_order_status(orderId)

Get order status by orderId.

int orderId : order ID

Return: String if order status is available. Otherwise, return None

roundToMinTick

roundToMinTick(price, minTick=0.01)

A convenient function to adjust a float number to fit the security’s minimum tick size requirement.

For example, roundToMinTick(1.1234, minTick=0.01) = 1.22 and roundToMinTick(1.1234, minTick=0.05) = 1.10

 

place_order_with_stoploss

place_order_with_stoploss (security, amount, stopLossPrice, style=MarketOrder())

Place an order with a stoploss order attached. The main order can be a market order, limit order or stop order. The attached stoploss order is a StopOrder. The stoploss order will be accepted by IB only after the main order is executed.

security: use symbol( ) or symbols( ) or superSymbol( ) to define security

amount: int, number of shares. If amount > 0, it is “buy” order. If amount < 0, it is “sell” order.

stopLossPrice: float, the stoploss price of the attached stop order

style: order type of the main order. It can be either MarketOrder, LimitOrder or StopOrder

Return: a tuple, (orderId, stoplossOrderId)

 

place_order_with_takeprofit

place_order_with_stoploss (security, amount, takeProfitPrice, style=MarketOrder())

Place an order with a takeprofit order attached. The main order can be a market order, limit order or stop order. The attached takeprofit order is a LimitOrder. The takeprofit order will be accepted by IB only after the main order is executed.

security: use symbol( ) or symbols( ) or superSymbol( ) to define security

amount: int, number of shares. If amount > 0, it is “buy” order. If amount < 0, it is “sell” order.

takeProfitPrice: float, the take profit price of the attached limit order

style: order type of the main order. It can be either MarketOrder, LimitOrder or StopOrder

Return: a tuple, (orderId, takeprofitOrderId)

 

place_order_with_stoploss_takeprofit

place_order_with_stoploss_takeprofit (security, amount, stopLossPrice, takeProfitPrice, style=MarketOrder())

Place an order with a stoploss order and a takeprofit order attached. The main order can be a market order, limit order or stop order. The attached stoploss order is a StopOrder.The attached takeprofit order is a LimitOrder. The stoploss order and the takeprofit order will be accepted by IB only after the main order is executed.

security: use symbol( ) or symbols( ) or superSymbol( ) to define security

amount: int, number of shares. If amount > 0, it is “buy” order. If amount < 0, it is “sell” order.

takeProfitPrice: float, the take profit price of the attached limit order

style: order type of the main order. It can be either MarketOrder, LimitOrder or StopOrder

Return: a tuple, (orderId, stoplossOrderid, takeprofitOrderId)

 

 

Rent-a-Coder