IBridgePy documentation



API documentation

initialize — similar as initialize at Quantopian


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


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


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)
  • stop order: order(security, amount, StopOrder(stopPrice)
  • trailing stop limit order: order(security, amount, TrailStopLimitOrder(stop_price, trailing_amount, limit_offset))

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


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

get_open_orders — similar as get_open_orders at Quantopian


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


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

get_datetime — similar as get_datetime at Quantopian


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


symbol — similar as symbol at Quantopian


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.

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


superSymbol(self, secType=None, symbol=None, currency=’USD’, exchange=’ ‘, primaryExchange=’ ‘, expiry=’ ‘, strike=-1, 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.

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

symbol: Symbol of securities that are defined by IB

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

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

primaryExchange: The primary exchange of the securities

expiry: Used for futures and options.

float strike: Strike price for futures and options.

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

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

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

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


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.


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’)]. 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.





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

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

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


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) or W (week), for example, ’10 D’ stands for 10 days

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.


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


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

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.


  • 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')



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

Return: a list of orderIds corresponding to the legs.



cancel_all_orders( )

Cancel all orders that are not executed yet.

Return: None



Close all positions in the account.

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

Return: None