IBridgePy documentation
- 1.3.1 cancel_all_orders
- 1.3.2 cancel_order
- 1.3.3 close_all_positions
- 1.3.4 get_all_open_orders
- 1.3.5 get_all_orders
- 1.3.6 get_open_orders
- 1.3.7 get_order
- 1.3.8 get_order_status
- 1.3.9 modify_order
- 1.3.10 order
- 1.3.11 order_percent
- 1.3.12 order_target
- 1.3.13 order_target_percent
- 1.3.14 order_target_value
- 1.3.15 order_value
- 1.3.16 place_order_with_stoploss
- 1.3.17 place_order_with_takeprofit
- 1.3.18 place_order_with_stoploss_takeprofit
- 1.3.19 order_status_monitor
- 1.3.20 place_combo_orders
- 1.4.1 data.current
- 1.4.2 data.history
- 1.4.3 request_historical_data
- 1.4.4 get_datetime
- 1.4.5 count_positions
- 1.4.6 get_all_positions
- 1.4.7 get_position
- 1.4.8 get_contract_details
- 1.4.9 get_scanner_results
- 1.4.10 show_account_info
- 1.4.11 show_real_time_price
- 1.4.12 show_real_time_size
- 1.4.13 show_timestamp
- 1.4.14 get_option_info
- 1.4.15 get_5_second_real_time_bar
RUN_ME.py: the main entry of IBridgePy
Related YouTube tutorials:
- Configuration system https://youtu.be/9hFZmCe7d4Q
accoundCode
accountCode is a required field in RUN_ME.py and users must put in their own accountCode there.
Note: accountCode is NOT as same as the login ID. To find out the accountCode in TWS or IB Gateway, please refer to this YouTube tutorial https://youtu.be/9hPOB-tY5vk
fileName
fileName is a required field in RUN_ME.py and users must choose only one fileName in RUN_ME.py file. The Python script that goes by this fileName in the folder of Strategies will be executed by IBridgePy. Absolute file path and relative file path are also supported.
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 only affect the output of get_datetime( )
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.
User interface
initialize
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
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_datafunction.
before_trading_start
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.
end
end()
The function is used to gracefully stop the running program without triggering the auto-re-connections.
schedule_function
schedule_function(func=None, date_rule=None, time_rule=None, calendar=None)
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 be used when runMode = ‘RUN_LIKE_QUANTOPIAN’ or ‘SUDO_RUN_LIKE_QUANTOPIAN’ or ‘REGULAR’
Automatically run a function on a predetermined schedule. Can only be called from inside initialize.
Related YouTube tutorials:
- Schedule function https://youtu.be/vXIQ1SJt_Bg
function 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_rules 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_rules 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)
- time_rules.spot_time(hour, minute, second) # run the function at specific spot time using US Eastern time zone. For example, (hour=9, minute=30, second=1) runs 9:30:01AM US/Eastern
calendars 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
Ordering
cancel_all_orders
cancel_all_orders( )
Cancel all orders that are not executed yet.
Return: None
cancel_order
cancel_order(order)
To cancel a specific order that has not been executed. Order can be either orderId or an instance of Order class.
Related YouTube tutorials:
- Cancel order https://youtu.be/TGUF6PVU6u0
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
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
get_all_open_orders
get_all_open_orders(accountCode=’default’ )
The method is to get all open orders from the given account, which does not include 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
get_all_orders
get_all_orders(accountCode=’default’ )
The method is to get all 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
get_open_orders
get_open_orders(security=None, accountCode=’default’)
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: Security object, created by either of symbol( ) or superSymbol( )
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
get_order
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.
get_order_status
get_order_status(orderId)
Get order status by orderId.
string orderId : order ID
Return: a string of Order Status if order status is available. Otherwise, return None
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.
Related YouTube tutorials:
- Place and modify orders https://youtu.be/zwoG8jSyU84
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
order
order(security, amount, style=MarketOrder ( ) , outsideRth=False, hidden=False,waitForFeedbackInSeconds=30, followUp=True, accountCode=’default’)
Place order to IB server. The default order type is market order. User needs to consider the margin requirement when placing any orders and the trading permissions that can be configured at IB’s account portal. If an order is placed but the user does not have the correct trading permission, the order will not be accepted by IB server and IBridgePy will terminate at 30 seconds because IB server will not send any responses.
Related YouTube tutorials:
- Place orders https://youtu.be/JkyxLYD2RBk
- Security object https://youtu.be/JkyxLYD2RBk
Security security: Security object, created by either of symbol( ) or superSymbol( )
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(symbol('AAPL'), 100)
Buy 100 shares of AAPL by placing a market order
- Limit order
order(symbol('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(symbol('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(symbol('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(symbol('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
- Trailing stop order:
order(symbol('AAPL'), 100, TrailStopOrder(stop_price=None, trailing_amount=None, trailing_percent=None, tif='DAY'))
- Market On Open (MOO):
from IBridgePy.OrderTypes import MarketOnOpenOrder
order(symbol('AAPL'), 100, MarketOnOpenOrder()))
- Market On Close (MOC):
from IBridgePy.OrderTypes import MarketOnCloseOrder
order(symbol('AAPL'), 100, MarketOnCloseOrder()))
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.
string accountCode: As an feature in IBridgePy Multi Account version, the order can be placed to different accounts(those accounts must be linked to a master IBKR account)
Return: a string representing orderId.
order_percent
order_percent (security, amount, style = MarketOrder ( ) , accountCode=’default’)
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).
string accountCode: As an feature in IBridgePy Multi Account version, the order can be placed to different accounts(those accounts must be linked to a master IBKR account)
Return: a string representing orderId.
order_target
order_target (security, amount, style = MarketOrder ( ), accountCode=’default’ )
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.
string accountCode: As an feature in IBridgePy Multi Account version, the order can be placed to different accounts(those accounts must be linked to a master IBKR account)
Return: a string representing orderId.
order_target_percent
order_target_percent (security, percent, style = MarketOrder ( ) , accountCode=’default’)
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.
string accountCode: As an feature in IBridgePy Multi Account version, the order can be placed to different accounts(those accounts must be linked to a master IBKR account)
Return: a string representing orderId.
order_target_value
order_target_value (security, value, style = MarketOrder ( ), accountCode=’default’ )
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.
string accountCode: As an feature in IBridgePy Multi Account version, the order can be placed to different accounts(those accounts must be linked to a master IBKR account)
Return: a string representing orderId.
order_value
order_value (security, value, style = MarketOrder ( ) , accountCode=’default’)
User needs to consider the margin requirement when placing market orders.
string accountCode: As an feature in IBridgePy Multi Account version, the order can be placed to different accounts(those accounts must be linked to a master IBKR account)
Return: a string representing orderId.
place_combo_orders
place_combo_orders (securities, amount, style=MarketOrder(), accountCode=’default’)
Place combo orders with multiple legs that are specified by a list of security objects. The security object must have valid values of conId, comboLegDirection and comboLegRatio.
Related YouTube tutorials:
- Coming soon
list of Security objects securities: a list of security objects defined by symbol( ) or superSymbol( ).
int amount: number of shares. It must be positive integers.
OrderType style: order type of the main order. It can be either MarketOrder, LimitOrder or StopOrder
string accountCode: As an feature in IBridgePy Multi Account version, the order can be placed to different accounts(those accounts must be linked to a master IBKR account)
Return: orderId
place_order_with_stoploss
place_order_with_stoploss (security, amount, stopLossPrice, style=MarketOrder(), tif=’DAY’, accountCode=’default’)
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
string tif: time-in-force for stoploss order. It can be “GTC”, “DAY”, etc.
string accountCode: As an feature in IBridgePy Multi Account version, the order can be placed to different accounts(those accounts must be linked to a master IBKR account)
Return: a tuple of (parent order ID, stoploss order ID)
place_order_with_takeprofit
place_order_with_stoploss (security, amount, takeProfitPrice, style=MarketOrder(), tif=’DAY’, accountCode=’default’)
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
string tif: time-in-force for the takeprofit order. It can be “GTC”, “DAY”, etc.
string accountCode: As an feature in IBridgePy Multi Account version, the order can be placed to different accounts(those accounts must be linked to a master IBKR account)
Return: a tuple, (parent order ID, takeprofit order ID)
place_order_with_stoploss_takeprofit
place_order_with_stoploss_takeprofit (security, amount, stopLossPrice, takeProfitPrice, style=MarketOrder(), tif=’DAY’, accountCode=’default’)
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
string tif: time-in-force for stoploss order and takeprofit order. It can be “GTC”, “DAY”, etc.
string accountCode: As an feature in IBridgePy Multi Account version, the order can be placed to different accounts(those accounts must be linked to a master IBKR account)
Return: a tuple, (parent order ID, stoploss order ID, takeprofit order ID)
order_status_monitor
order_status_monitor (ibpyOrderId, target_status, waitingTimeInSecond=30)
order_status_monitor is used to follows up on the status of the order that is sent to brokers for execution. IBridgePy will terminate the code for users to investigate issues if the expected order status is not confirmed by the broker within a default of 30 seconds.
Related YouTube tutorials:
- Introduction to place orders and modify orders https://youtu.be/zwoG8jSyU84
string ibpyOrderId: the order ID of the order to follow up on order status
string or list of string target_status: the expected order status or a list of expected order status. IBridgePy will continue to execute if the expected order status is confirmed by the broker. Otherwise IBridgePy will terminate execution for user to investigate the potential issues.
int waitingTimeInSeconds: IBridgePy will wait for up to a default of 30 seconds to monitor the order status from the brokers. If the expected order status is confirmed, IBridgePy will jump out of this method and continue the code execution.
Return: None
Get info
data.current
data.current(security, fields)
Returns the real time value of the given securities for the given fields. This method is outdated and recommended way is to to use show_real_time_price
Security security: Security object, created by either of symbol( ) or superSymbol( )
string or list[string] fields: Valid values are ‘ask_price’, ‘bid_price’, ‘ask_size’, ‘bid_size’, ‘price’, ‘last_price’, ‘open’, ‘high’, ‘low’, ‘close’ and ‘volume’.
Return
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
data.history(security, fields, bar_count, frequency, followUp=True)
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. The method is outdated and recommend to use request_historical_data
Related YouTube tutorials:
- Request_historical_data https://youtu.be/7jmHRVsRcI0
- Save historical data to local files while gracefully handling errors https://youtu.be/Vuf7Jb9-hCk
- Request historical data of other than U.S. equities and handle “No data permission” and “No security definition” https://youtu.be/iiRierq6sTU
- Request historical data of FOREX, provided by Interactive Brokers for free https://youtu.be/7jmHRVsRcI0
- Handle errors related to request hist https://youtu.be/Mq9SUX-iwS4
Security security: Security object, created by either of symbol( ) or superSymbol( )
string or list[string] fields: 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
bool followUp: The default value is True, which means that IBridgePy will regularly check if the expected data have been received and raise errors after IBridgePy waits for more then 30 seconds(default value=waitForFeedbackInSeconds). If the value of followUp is set to False, it means that IBridgePy will not follow up on the status of the request.
Return
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.
request_historical_data
request_historical_data(security, barSize, goBack, endTime=’default’, whatToShow=None, useRTH=1, waitForFeedbackInSeconds=30, timezoneOfReturn=pytz.timezone(‘US/Eastern’), followUp=True)
To obtain historical data from IB. IB’s historical data is adjusted for splits, but not dividends. Holidays and weekends will not be counted.
Related YouTube tutorials:
- Request_historical_data https://youtu.be/7jmHRVsRcI0
- Save historical data to local files while gracefully handling errors https://youtu.be/Vuf7Jb9-hCk
- Request historical data of other than U.S. equities and handle “No data permission” and “No security definition” https://youtu.be/iiRierq6sTU
- Download historical data convert to epoch index https://youtu.be/hYL6SYgy7wE
- Download historical data and make a machine learning https://youtu.be/hNCwNxeXrwA
- Request historical data of FOREX, provided by Interactive Brokers for free https://youtu.be/7jmHRVsRcI0
- Handle errors related to request hist https://youtu.be/Mq9SUX-iwS4
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.
Note: 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 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.
bool followUp: The default value is True, which means that IBridgePy will regularly check if the expected data have been received and raise errors after IBridgePy waits for more then 30 seconds(default value=waitForFeedbackInSeconds). If the value of followUp is set to False, it means that IBridgePy will not follow up on the status of the request.
Return: A python pandas dataFrame will be returned. columns are “open”, “high”, “low”, “close” and “volume” and index is python datetime or date. If the value of follwUp is set to False and there is no response, the returned value is None.
Exception: Raise RuntimeError if IB data server does not respond due to connectivity issues within a few seconds, defined by waitForFeedbackInSeconds. Other than connectivity issues, IBridgePy will terminate execution.
get_datetime
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.
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: Decimal, positive number = long position; negative number = short position.
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.
get_option_info
get_option_info(security, field, waitForFeedbackInSeconds=30)
The method is to get the information for an option.
Security security: An Option security object, created by the function of superSymbol( ).
string field: Valid values are ‘delta’, ‘gamma’, ‘vega’, ‘theta’, ‘impliedVol’, ‘optPrice’, ‘undPrice’, ‘option_call_open_interest’ and ‘option_put_open_interest’.
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.
Return: a dictionary that the key is the field and the value is the value for the field.
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 Position object.
get_contract_details
get_contract_details(secType, symbol, field, currency=’USD’, exchange=”, primaryExchange=”, expiry=”, strike=0.0, right=”, multiplier=”, localSymbol=”, waitForFeedbackInSeconds=30)
IB provides a Contract and Symbol database for users to find desired contracts. This 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.
Related YouTube tutorials:
- get_contract_details https://youtu.be/bXScQPlDP-c
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.
int waitForFeedbackInSeconds: IBridgePy keeps monitoring the responses from IB server and will give up after a number of seconds. It may take much longer than 30 seconds for some requests to complete. Therefore, users may adjust this number to keep IBridgePy waiting for a longer time.
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 check out this tutorial on YouTube for detailed examples.
get_scanner_results
get_scanner_results(waitForFeedbackInSeconds=30, **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.
Related YouTube tutorials:
- Find the most active stocks https://youtu.be/0sU4R1fIN3Y
int waitForFeedbackInSeconds: IBridgePy keeps monitoring the responses from IB server and will give up after a number of seconds. It may take much longer than 30 seconds for some requests to complete. Therefore, users may adjust this number to keep IBridgePy waiting for a longer time.
**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’. The meaning of these scanCode are here: https://www.interactivebrokers.com/en/software/tws/usersguidebook/technicalanalytics/market_scanner_types.htm
Return: a pandas DataFrame containing two columns, rank and Security objects. The security objects can be used as input to other methods, such as placing order.
show_account_info
show_account_info(field, accountCode=’default’)
The method is to show account information that is specified by the field name.
Related YouTube tutorials:
- Intro to show_account_info https://youtu.be/tXjI-ozt-R4
string field: the field name. The field name can be NetLiquidation, TotalCashValue, GrossPositionValue and BuyingPower. The full list from IB: IB doc here. For TD, only these 4 values are accepated.
string accountCode: user can specify the account code in IBridgePy Multi-Acc version
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( ).
Related YouTube tutorials:
- Show real time prices https://youtu.be/O_lNWAXMLHw
- Security object https://youtu.be/JkyxLYD2RBk
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
- high: return the high price of the security within the current date
- low: return the low price of the security within the current date
- close: return the close price of the security in the previous trading day
- open: return the open price of the security for the current trading session(typically it is the current day)
Return: float, -1 means the real tim price is not available at the moment.
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
Return:
- bid_size: Decimal
- ask_size: Decimal
- volume: Decimal
show_timestamp
show_timestamp(security, param)
The method is to show when a price of a security was received by IBridgePy, or call it the timestamp of the price.
Related YouTube tutorials:
- Into to show_timestamp and get today’s open price https://youtu.be/syT-Kria7rk
Security security: A Security object, created by the function of symbol( ) or superSymbol( ).
string param: the parameter name of security. The field name can be ask_price, bid_price, last_price, open, high, low and close.
Return: datetime.datetime with timezone. The default timezone is US/Eastern.
get_5_second_real_time_bar
get_5_second_real_time_bar(security, tickType)
The method is to get 5 second real time bar, a feature related to Interactive Brokers only.
Related YouTube tutorials:
- Into to get 5 second real time bar
Security security: A Security object, created by the function of symbol( ) or superSymbol( ).
string tickType: The field can be ASK, BID, TRADES or MIDPOINT.
Return: a dict with the following keys: time, open, high, low, close, volume, wap, count and timestamp
Tools
roundToMinTick
roundToMinTick(price, minTick=0.01)
A convenient tool to covert a number to compliant with a minimum tick. Typically, it is used to place orders when limit prices or stop prices have to follow the rules of the minimum price variation set by IB. A typical error message related to the minimum price variation looks like this: “The price does not conform to the minimum price variation for this contract.”
For example,
- roundToMinTick(123.0222, minTick=0.01) = 123.02
- roundToMinTick(123.0222, minTick=5) = 120
- roundToMinTick(-123.0222, minTick=5) = -120
Note to traders: When using roundToMinTick to convert prices, a trader needs to consider if the floor function or the ceil function fits the needs. When the price is positive, the result is the same as the floor function. When the price is negative, it is similar to the concept of ceil.
float price: a number, typically related to a price.
float minTick: the minimum price variation for a contract. Refer to IB’s official contract database.
Return: a float.
get_ibpy_expiry_in_days
get_ibpy_expiry_in_days()
Return the number of days that the current subscription will expire.
Return: int.
send_email
send_email(emailTitle, emailBody, toEmail=None)
A convenient way to send out email. User needs to follow the YouTube tutorial to configure apiKey. To send out multiple emails, the function can be invoked many times.
Related YouTube tutorials:
- Config apiKey and send out emails: https://youtu.be/jkeos2QrkfQ
string emailTitle: email title.
string emailBody: email body.
string toEmail: to the email address. If toEmail is None, the default toEmail is the user’s registered email.
Return: None
Others
symbol
symbol(ticker)
The method to create a Security object.
Related YouTube tutorials:
- Introduction to symbol: https://youtu.be/QHj9AJLhg9c
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’
symbols
symbols(‘symbol1′,’symbol2’, ‘symbol3’,…)
Create a list of security objects. All of the symbols should follow the pre-determined format.
superSymbol
superSymbol(secType=None, symbol=None, currency=’USD’, exchange=” “, primaryExchange=” “, expiry=” “, strike=0.0, right=” “, multiplier=” “, includeExpired=False, conId=0, localSymbol=” “, tradingClass=” “)
Create a security object by clearly defining every detail. It can be used to define any securities/commodities that are available at IB.
Related YouTube tutorials:
- Introduction about IB’s official contract database: https://youtu.be/cvIRr4xokfo
- Fill in for superSymbol: https://youtu.be/QHj9AJLhg9c
- The contract description specified for SPX is ambiguous: https://youtu.be/T2pyz7Z-VsI
- tradingClass: https://youtu.be/pCDLfLL0WRo
To know the details of a contract/security, IB provides a contract/security database search: https://pennies.interactivebrokers.com/cstools/contract_info/v3.10/index.php
string secType: STK(stock), OPT(options), FUT(futures), IND(index), CASH(forex), FOP(future options) 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.
string comboLegDirection: either “BUY” or “SELL”. It is used only for placing combo orders.
int comboLegRatio: the ratio between different legs when placing combo orders. The default value is 1.
string tradingClass: For IB’s API, trading classes act as another layer for the unique identification of securities which otherwise might be ambiguous.
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:
please use symbol, instead of superSymbol
symbol('CASH, EUR, 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)
record
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.
Context
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)
context.portfolio.positions
context.portfolio.portfolio_value
context.portfolio.positions_value
context.portfolio.cash
The recommended way to access account information is to use show_account_info
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):
# Not all of cash can be used for trade because pending orders, if any, will decrease the portfolio margin.
print (context.portfolio.portfolio_value) print (context.portfolio.positions_value) print (context.portfolio.cash) end()
Position object
The Position object is to represent account’s current position. The positions do not have status, such as open position or closed position because positions are a number of shares of securities holding in the account.
Decimal amount: the number of shares that the account is holding for that contract
float cost_basis: the cost basis of the position
For example:
position = get_position(symbol('SPY')) print(position.amount) print(position.cost_basis)
Order object
The Order object is to represent the orders that the account has placed. Order can have different status, such as “Filled”, “Submitted”, etc.
string orderId: the id to identify this order
string status: Possible values are PendingSubmit, PendingCancel, PreSubmitted, Submitted, Cancelled, Filled and Inactive. Check out here for more details.
int amount: The number of shares in the order.
int filled: the number of shares that has been filled.
int remaining: the number of shares that has not been filled.
float avgFillPrice: the average filled price of this order that has been filled. Note: The order can be partially filled.
float lastFillPrice: the last fill price of this order. Note: The order can be partially filled.
string action: either Buy or Sell.
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