IBridgePy documentation

Contents

Methods

RUN_ME.py: the main entry of IBridgePy

runMode

There are a few options for runMode:
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_QUSNTOPIAN: 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 not changed by user.

Outside the U.S market trading time period, the message will show up “MarketManager::Market is closed but IBridgePy is still running”, which means that handle_data ( ) is not triggered every minute when the U.S. market is closed and IBridgePy is still running without warning or errors.

SUDO_RUN_LIKE_QUSNTOPIAN: The difference between this mode and run_like quantopian mode is that handle_data ( ) is triggered every minute regardless of U.S. market time.

logLevel

ERROR : You will only see error messages from IB server.

INFO (default): You will see error messages plus info messages. This is the default value.

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

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

showTimeZone

The default timezone is “US/Eastern”. It will affect the output of get_datetime( ), request_historical_data ( ) and data.history ( )

If user wants to set a timezone, this line can be added in the RUN_ME.py

showTimZone = “US/Pacific”

marketName

The default marketName is “NYSE”. handle_data ( ) will be executed following NYSE market calendar in the runMode of “run_like_quantopian”.

The other marketNames that IBridgePy supports are “CME”, “ICE”, “CFE”, “BMF”, “LSE”, “TSX” and “EUREX”.

These market calendars are regular market schedules and special events are not inclusively considered.

Rent a Coder service

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

Rent a Coder service


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.

Rent a Coder service

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.

Rent a Coder service

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

Rent a Coder service


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. Holidays and weekends will not be counted.

security: Security object, created by either of symbol( ) 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.

Rent a Coder service


order — similar as order at Quantopian

order(security, amount, style=MarketOrder ( ) , outsideRth=False, hidden=False,waitForFeedbackInSeconds=30, followUp=True)

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

Security security: Security object, created by either of symbol( ) 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.

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

IBridgePy supports the following order types:

  • Market order
order(symbole('AAPL'), 100)

Buy 100 shares of AAPL by placing a market order

  • Limit order
order(symbole('AAPL'), 100, LimitOrder(limit_price=99.90)

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(symbole('AAPL'), 100, StopOrder(stop_price=99.80)

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

  • Stop Limit Order
order(symbole('AAPL'), 100, StopLimitOrder(limit_price=99.90, stop_price=99.80, tif = 'DAY'))

Assume that trader has a position of 100 shares of ‘AAPL’ and the cost basis is $105.00. The trader wants to place a stop loss at $99.80 by placing a limit order that is triggered when the price touches $99.90.

  • Trailing stop limit order:
order(symbole('AAPL'), 100, TrailStopLimitOrder(stop_price, limit_offset, trailing_amount=None, trailing_percent=None, tif = 'DAY'))

stop_price and limit_offset are required. Either trailing_amount or trailing_percent is required but not both. More details about trailing stop limit order is here https://www.interactivebrokers.com/en/index.php?f=606

An example code is provided here.

  • Trailing stop order:
order(symbole('AAPL'), 100, TrailStopOrder(stop_price=None, trailing_amount=None, trailing_percent=None, tif = 'DAY'))

More details about trailing stop order is here https://www.interactivebrokers.com/en/index.php?f=605

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.

bool hidden: IB allows to place hidden orders at the exchange of ISLAND. Set it to True when placing a hidden order.

int waitForFeedbackInSeconds: IBridgePy continuously checks if the order has been accepted by IB server. If the expected response is not received with a number of seconds, specified by waitForFeedbackInSeconds, IBridgePy will terminate the program for users to inspect any potential issues. 

bool followUp: IBridgePy continuously checks the order status and terminates the code if abnormality is detected. However, it may cause delays when placing multiple orders at same time. If this value is set to False, IBridgePy will not monitor the order status. User can still use order_status_monitor to follow up on the order status later and it is highly recommended.

Return: int, orderId. “-1” means that there is no order has been placed.

Rent a Coder service

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.

Rent a Coder service

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.

!!! The function assumes that the base current is USD. It will lead to errors if the base current is not USD.

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

Rent a Coder service

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. 

!!! The function assumes that the base current is USD. It will lead to errors if the base current is not USD.

Rent a Coder service

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.

Rent a Coder service

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.

!!! The function assumes that the base current is USD. It will lead to errors if the base current is not USD.

Rent a Coder service

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: reqId.*

* 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

Rent a Coder service

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

Rent a Coder service

get_order  — similar as get_order at Quantopian

get_order(orderId)

int OrderId: order id

Return: An Order object with the given orderId. The Order object is discarded at the end of handle_data.

Rent a Coder service

get_datetime — similar as get_datetime at Quantopian

get_datetime(timezone=’default’)

Get the current datetime of IB system similar to that defined in Quantopian. The exhaust list of timezone is here.

string timezone: a timezone defined by pytz.timezone. For example, timezone = “US/Pacific”. The default timezone is “US/Eastern”.

Return: a python Datetime with a timezone.

Rent a Coder service

symbol — similar as symbol at Quantopian

symbol(ticker)

The method to create a Security object.

string ticker: the ticker or symbol of the contract.

Return: an instance of Security.

Example

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’

 

Rent a Coder service

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.

Rent a Coder service

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’ or ‘SUDO_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

Rent a Coder service

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

Return: None.

superSymbol

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

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

To know the details of a contract/security, IB provides a contract/security database search.

https://www.interactivebrokers.com/en/index.php?f=463

string secType: STK, OPT, FUT, IND, CASH, etc.

string 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

int conId: The unique contract’s identifier, defined by Interactive Brokers.

string localSymbol: The contract’s symbol within its primary exchange.

For example:

Stock of Apple Inc. using IB Smart routing:

superSymbol(secType='STK', symbol='AAPL', currency='USD', exchange='SMART', primaryExchange='NASDAQ')

ETF of SPY, traded at Singapore Exchange and its local symbol is S27:

superSymbol(secType='STK', symbol='',currency='USD', exchange='SGX', primaryExchange='SGX', localSymbol='S27')

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.0, right='C', multiplier='100', includeExpired=True)

Structured Product:

superSymbol(secType='IOPT', symbol='', currency='HKD', expiry='20190129', exchange='SEHK', localSymbol='61084',
right='P', multiplier='0.0000833333', strike=28388.0)

Rent a Coder service

show_real_time_price

show_real_time_price(security, param)

The method is to request real time quotes of the specified security from IB 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 IB server and the real time prices will come back automatically until the request is cancelled. If needed, you can call show_real_time_price( ) in initialize( ).

Security security: A Security object, created by the function of symbol( ) or superSymbol( ).
string param:

  • 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

Return: float, -1 means the real tim price is not available at the moment.

Rent a Coder service

show_real_time_size

show_real_time_size(security, param)

The method is to request real time size of the specified security from IB 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 IB server and the real time prices will come back automatically until the request is cancelled. If needed, you can call show_real_time_size( ) in initialize( ).

Security security: A Security object, created by the function of symbol( ) or superSymbol( ).
string param:

  • 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: int

Rent a Coder service

get_all_orders

get_all_orders(accountCode=’default’ )

The method is to get all open orders from the given account, including canceled orders and inactive orders.

string accountCode: user can specify the account code in IBridgePy Multi-Acc version

Return: a dictionary that the key is orderId and the value is Order object

Rent a Coder service

get_all_positions

get_all_positions(accountCode=’default’ )

The method is to get all positions from the given account.

string accountCode: user can specify the account code in IBridgePy Multi-Acc version

Return: a dictionary that the key is Security object and the value is Position object.

Rent a Coder service

get_position

get_position(security, accountCode=’default’ )

The method is to get the position object of a given security from the given account.

Security security:A Security object, created by the function of symbol( ) or superSymbol( ).

string accountCode: user can specify the account code in IBridgePy Multi-Acc version

Return: a dictionary that the key is Security object and the value is Position object.

Rent a Coder service

get_contract_details

get_contract_details(secType, symbol, field, currency=’USD’, exchange=”, primaryExchange=”, expiry=”, strike=0.0, right=”, multiplier=”, localSymbol=”)

IB provides a Contract and Symbol database for users to find desired contractsThis function can be used to get contract details from IB’s contact database. The link to IB’s Contract and Symbol database is here. The input parameters, not including “field”, are used to make a criterion to query IB’s Contract and Symbol database. “field” is used to specify the attributes of the found contracts.

string secType: security type, such as “STK”- stock, “OPT”-options, “FUT”-futures, “CASH”-forex, etc.

string symbol: the ticker of the security / contract.

string or list[string] field: use specify which field(s) is queried. The following fields of Contract are options: ‘conId’, ‘symbol’, ‘secType’, ‘LastTradeDateOrContractMonth’, ‘strike’, ‘right’, ‘multiplier’,
‘exchange’, ‘currency’, ‘localSymbol’, ‘primaryExchange’, ‘tradingClass’, ‘includeExpired’,
‘secIdType’, ‘secId’, ‘comboLegs’, ‘underComp’, ‘comboLegsDescrip’, ‘marketName’, ‘minTick’, ‘priceMagnifier’, ‘orderTypes’, ‘validExchanges’, ‘underConId’, ‘longName’, ‘contractMonth’, ‘industry’, ‘category’, ‘subcategory’, ‘timeZoneId’, ‘tradingHours’, ‘liquidHours’, ‘evRule’, ‘evMultiplier’, ‘mdSizeMultiplier’, ‘aggGroup’, ‘secIdList’, ‘underSymbol’, ‘underSecType’, ‘marketRuleIds’, ‘realExpirationDate’, ‘cusip’, ‘ratings’, ‘descAppend’, ‘bondType’, ‘couponType’, ‘callable’, ‘putable’, ‘coupon’, ‘convertible’, ‘maturity’, ‘issueDate’, ‘nextOptionDate’, ‘nextOptionType’, ‘nextOptionPartial’,
‘notes’. The returned value may be null depending on security type.

string currency: base currency of the contract.

string exchange: the exchange for the contract. It is mainly used to query futures and option chains.

string primaryExchange: the primary exchange of the contract.

string expiry: the expiry of the contract. It is mainly used to query futures and option chains.

float strike: the strike of the contract. It is mainly used to query option chains.

string right: either “C”-call or “P”-put. It is mainly used to query option chains.

string multiplier: the multiplier of the contract. It is mainly used to query futures and option chains.

string localSymbol: the local symbol of the contract. It is mainly used to query non- US contracts.

Return: a dictionary that the key is field name and the value is returned value. Or a panda DataFrame when the function is used to search futures and option chains.

Example: Please see the IBridgePy tutorial for detailed examples.

Rent a Coder service

get_scanner_results

get_scanner_results(**kwargs)

IBridgePy provides an easy way to scan relevant markets and return the top contracts based on the instrument, parameter and filtering criteria that user defines.

**kwargs: The following field names are the possible choices. ‘numberOfRows’, ‘instrument’, ‘locationCode’, ‘scanCode’, ‘abovePrice’, ‘belowPrice’,  ‘aboveVolume’, ‘marketCapAbove’, ‘marketCapBelow’, ‘moodyRatingAbove’, ‘moodyRatingBelow’, ‘spRatingAbove’, ‘spRatingBelow’,
‘maturityDateAbove’, ‘maturityDateBelow’, ‘couponRateAbove’, ‘couponRateBelow’, ‘excludeConvertible’, ‘averageOptionVolumeAbove’, ‘scannerSettingPairs’, ‘stockTypeFilter’.

Return: a pandas DataFrame containing the Contracts according to the filtering criteria that user defines.

Example: Please see the IBridgePy tutorial for detailed examples.

Rent a Coder service

request_historical_data

request_historical_data(security, barSize, goBack, endTime=’default’, whatToShow=None, useRTH=1, formatDate=2, waitForFeedbackInSeconds=30, timezoneOfReturn=pytz.timezone(‘US/Eastern’)

To obtain historical data from IB. IB’s historical data is adjusted for splits, but not dividends. Holidays and weekends will not be counted.

Security security: use symbol( ) 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: number of seconds that IBridgePy waits for feedbacks from IB server. IBridgePy will terminate if it has not received the expected feedbacks from IB servers after the specified seconds.

pytz.timezone timezoneOfReturn: the index of the returned pandas DataFrame is in the type of datetime.datetime with a timezone. User can specify the timezone for their convenience.

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

Rent a Coder service

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.

string action: “BUY” or “SELL”

int amount: number of shares, must be a positive number.

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

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

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

int 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

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

int parentId: Designate an order ID for the parent order when it is needed. Typically it is used for bracket and auto trailing stop orders.

Return: an instance of Order.

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

Rent a Coder service

place_combination_orders

place_combination_orders(legList)

Place orders that user specifically defines. IBridgePy does not automatically monitor if the order status has been received from IB server.

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

Return: a list of order IDs corresponding to the legs.

orderId1, orderId2, orderId3 = place_combination_orders([leg0, leg1, leg2])

Rent a Coder service

cancel_all_orders

cancel_all_orders( )

Cancel all orders that are not executed yet.

Return: None

Rent a Coder service

close_all_positions

close_all_positions(orderStatusMonitor=True)

Close all positions in the account.

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

Return: None

Rent a Coder service

count_positions

count_positions(security)

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

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

Return: int, positive number = long position; negative number = short position.

Rent a Coder service

order_status_monitor

order_status_monitor(orderId, target_status, waitingTimeInSeconds=30)

Keep monitoring the status of an order given by orderId. Terminate the code if the expected target_status is not received within 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.

Note: this method may block other actions because it keeps monitoring the status of an given order and other codes cannot be executed at the same time. To unblock placing other time-sensitive orders, user may place multiple orders at first place and then monitor the order status.

int orderId : order ID returned from order functions.

string or list[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.

Rent a Coder service

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

Rent a Coder service

roundToMinTick

roundToMinTick(price, minTick=0.01)

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

float price: a price.

float minTick: the minimum tick to be applied to format the price.

Return: float. For example, roundToMinTick(1.1234, minTick=0.01) = 1.22 and roundToMinTick(1.1234, minTick=0.05) = 1.10

Rent a Coder service

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 security: use symbol( ) or superSymbol( ) to define security

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

float stopLossPrice: the stoploss price of the attached stop order

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

Return: a tuple of (parent order ID, stoploss order ID)

Rent a Coder service

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 security: use symbol( ) or superSymbol( ) to define security

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

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

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

Return: a tuple, (parent order ID, takeprofit order ID)

Rent a Coder service

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 security: use symbol( ) or superSymbol( ) to define security

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

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

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

Return: a tuple, (parent order ID, stoploss order ID, takeprofit order ID)

Rent a Coder service

modify_order

modify_order(orderId, newQuantity=None, newLimitPrice=None, newStopPrice=None, newTif=None, newOrderRef=None, newOcaGroup=None, newOcaType=None)

Modify an order that has been placed by the same client. The parameters of the order to be modified are quantity, limitPrice, stopPrice, tif (time in force), and orderRef. These parameters can be modified at same time by this function.

int orderId: orderId of the order to be modified.

int newQuantity: new quantity, number of shares.

float newLimitPrice: new limit price.

float newStopPrice: new stop price.

string newTif: new tif, time in force, such as “DAY”, “GTC”, etc.

string newOrderRef: new orderRef, a label that users can customize.

string newOcaGroup: new one-cancel-all group, a group name

int newOcaType: Tells how to handle remaining orders in an OCA group when one order or part of an order executes. Valid values are:
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 block.

Return: None

Rent a Coder service

 

Objects

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.

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

1. To get the cost basis of a position of AAPL:

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

2. To get number of shares of a position of AAPL in a portfolio:

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

3. To know the total number of positions in a portfolio:

totalNumberOfPositions = len(context.portfolio.positions)

4. To get a list of securities with open positions:

allSecurities = context.portfolio.positions.keys( )

5. To iterate all securities with open positions:

for security, position in context.portfolio.positions.items( ):

print(security, position)

Rent a Coder service

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.

Not all of cash can be used for trade because pending orders, if any, will decrease portfolio margin

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

Rent a Coder service

Others

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. PreSubmitted orders will reduce portfolio margin.
  • Submitted: The order has been accepted. Submitted orders will reduce portfolio margin.
  • 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