Bulletins Copy Location
Copy Location
From time to time, IB sends out important News Bulletins, which can be accessed via the TWS API through the EClient.reqNewsBulletins. Bulletins are delivered via IBApi.EWrapper.updateNewsBulletin whenever there is a new bulletin. In order to stop receiving bulletins you need to cancel the subscription.
Request IB Bulletins Copy Location
Copy Location
EClient.reqNewsBulletins (
allMessages: bool. If set to true, will return all the existing bulletins for the current day, set to false to receive only the new bulletins.
)
Subscribes to IB’s News Bulletins.
self.reqNewsBulletins(True)
client.reqNewsBulletins(true);
m_pClient->reqNewsBulletins(true);
client.reqNewsBulletins(true);
client.reqNewsBulletins(True)
Receive IB Bulletins Copy Location
Copy Location
EWrapper.updateNewsBulletin (
msgId: int. The bulletin’s identifier.
msgType: int. 1: Regular news bulletin; 2: Exchange no longer available for trading; 3: Exchange is available for trading.
message: String. The news bulletin context.
origExchange: String. The exchange where the message comes from.
)
Provides IB’s bulletins
def updateNewsBulletin(self, msgId: int, msgType: int, newsMessage: str, originExch: str): print("News Bulletins. MsgId:", msgId, "Type:", msgType, "Message:", newsMessage, "Exchange of Origin: ", originExch)
@Override public void updateNewsBulletin(int msgId, int msgType, String message, String origExchange) { System.out.println("News Bulletin: " + EWrapperMsgGenerator.updateNewsBulletin( msgId, msgType, message, origExchange)); }
void TestCppClient::updateNewsBulletin(int msgId, int msgType, const std::string& newsMessage, const std::string& originExch) { printf( "News Bulletins. %d - Type: %d, Message: %s, Exchange of Origin: %sn", msgId, msgType, newsMessage.c_str(), originExch.c_str()); }
public virtual void updateNewsBulletin(int msgId, int msgType, String message, String origExchange) { Console.WriteLine("News Bulletins. "+msgId+" - Type: "+msgType+", Message: "+message+", Exchange of Origin: "+origExchange+"n"); }
Public Sub updateNewsBulletin(msgId As Integer, msgType As Integer, message As String, origExchange As String) Implements IBApi.EWrapper.updateNewsBulletin Console.WriteLine("News Bulletins. " & msgId & " - Type: " & msgType & ", Message: " & message & ", Exchange of Origin: " & origExchange) End Sub
Cancel Bulletin Request Copy Location
Copy Location
EClient.cancelNewsBulletin ()
Cancels IB’s news bulletin subscription.
self.cancelNewsBulletins()
client.cancelNewsBulletins();
m_pClient->cancelNewsBulletins();
client.cancelNewsBulletin();
client.cancelNewsBulletin()
Contracts (Financial Instruments) Copy Location
Copy Location
An IBApi.Contract object represents trading instruments such as a stocks, futures or options. Every time a new request that requires a contract (i.e. market data, order placing, etc.) is sent to TWS, the platform will try to match the provided contract object with a single candidate.
The Contract Object Copy Location
Copy Location
The Contract object is an object used throughout the TWS API to define the target of your requests. Contract objects will be used for market data, portfolios, orders, executions, and even some news request. This is the staple structure used for all of the TWS API.
In all contracts, the minimum viable structure requires at least a conId and exchange, or a symbol, secType, exchange, primaryExchange, and currency. Derivatives will require additional fields, such as lastTradeDateOrExpiration, tradingClass, multiplier, strikes, and so on.
The values to the right represent the most common Contract values to pass for complete contracts. For a more comprehensive list of contract structures, please see the Contracts page.
Contract()
ConId: int. Identifier to specify an exact contract.
Symbol: String. Ticker symbol of the underlying instrument.
SecType: String. Security type of the traded instrument.
Exchange: String. Exchange for which data or trades should be routed.
PrimaryExchange: String. Primary listing exchange of the instrument.
Currency: String. Base currency the instrument is traded on.
LastTradeDateOrContractMonth: String. For derivatives, the expiration date of the contract.
Strike: double. For derivatives, the strike price of the instrument.
Right: String. For derivatives, the right (P/C) of the instrument.
TradingClass: String. For derivatives, the trading class of the instrument.
May be used to indicate between a monthly or a weekly contract.
Given additional structures for contracts are ever evolving, it is recommended to review the relevant Contract class in your programming language for a comprehensive review of what fields are available.
{TWS API}sourcepythonclientibapicontract.py
{TWS API}sourceJavaClientcomibclientContract.java
{TWS API}sourceCppClientclientContract.h
{TWS API}sourceCSharpClientclientContract.cs
Depending on the Excel structure used, either C# or Java file path will be used.
For ActiveX and RTD, see C#
For DDE, see Java.
Finding Contract Details in Trader Workstation Copy Location
Copy Location
If there is more than one contract matching the same description, TWS will return an error notifying you there is an ambiguity. In these cases the TWS needs further information to narrow down the list of contracts matching the provided description to a single element.
The best way of finding a contract’s description is within the TWS itself. Within the TWS, you can easily check a contract’s description either by double clicking it or through the Contract Info -> Description menu, which you access by right-clicking a contract in TWS:
The description will then appear:
Note: you can see the extended contract details by choosing Contract Info -> Details. This option will open a web page showing all available information on the contract.
Whenever a contract description is provided via the TWS API, the TWS will try to match the given description to a single contract. This mechanism allows for great flexibility since it gives the possibility to define the same contract in multiple ways.
The simplest way to define a contract is by providing its symbol, security type, currency and exchange. The vast majority of stocks, CFDs, Indexes or FX pairs can be uniquely defined through these four attributes. More complex contracts such as options and futures require some extra information due to their nature. Below are several examples for different types of instruments.
Contract Details Copy Location
Copy Location
Complete details about a contract in IB’s database can be retrieved using the function IBApi.EClient.reqContractDetails. This includes information about a contract’s conID, symbol, local symbol, currency, etc. which is returned in a IBApi.ContractDetails object. reqContractDetails takes as an argument a Contract object which may uniquely match one contract, and unlike other API functions it can also take a Contract object which matches multiple contracts in IB’s database. When there are multiple matches, they will each be returned individually to the function IBApi::EWrapper::contractDetails.
Request for Bond details will be returned to IBApi::EWrapper::bondContractDetails instead. Because of bond market data license restrictions, there are only a few available fields to be returned in a bond contract description, namely the minTick, exchange, and short name.
Note: Invoking reqContractDetails with a Contract object which has currency = USD will only return US contracts, even if there are non-US instruments which have the USD currency.
Another function of IBApi::EClient::reqContractDetails is to request the trading schedule of an instrument via the TradingHours and LiquidHours fields. The corresponding timeZoneId field will then indicate the time zone for the trading schedule of the instrument. TWS sends these timeZoneId strings to the API from the schedule responses as-is, and may not exactly match the time zones displayed in the TWS contract description.
Possible timeZoneId values are: Europe/Riga, Australia/NSW, Europe/Warsaw, US/Pacific, Europe/Tallinn, Japan, US/Eastern, GB-Eire, Africa/Johannesburg, Israel, Europe/Vilnius, MET, Europe/Helsinki, US/Central, Europe/Budapest, Asia/Calcutta, Hongkong, Europe/Moscow, GMT
Request Contract Details Copy Location
Copy Location
EClient.reqContractDetails (
reqId: int. Request identifier to track data.
contract: ContractDetails. the contract used as sample to query the available contracts.
Typically contains at least the Symbol, SecType, Exchange, and Currency.
)
Receives the full contract’s definitions This method will return all contracts matching the requested via EClientSocket::reqContractDetails. For example, one can obtain the whole option chain with it.
self.reqContractDetails(reqId, contract)
client.reqContractDetails(reqId, contract)
m_pClient->reqContractDetails(reqId, contract);
client.reqContractDetails(reqId, contract);
client.reqContractDetails(reqId, contract)
Receive Contract Details Copy Location
Copy Location
EWrapper.contractDetails (
reqId: int. Request identifier to track data.
contract: ContractDetails. Contains the full contract object contents including all information about a specific traded instrument.
)
Receives the full contract’s definitions This method will return all contracts matching the requested via EClientSocket::reqContractDetails. For example, one can obtain the whole option chain with it.
def contractDetails(self, reqId: int, contractDetails: ContractDetails): printinstance(reqId, contractDetails)
@Override public void contractDetails(int reqId, ContractDetails contractDetails) { System.out.println(EWrapperMsgGenerator.contractDetails(reqId, contractDetails)); }
void TestCppClient::contractDetails( int reqId, const ContractDetails& contractDetails) { printf( "ContractDetails. ReqId: %dn", reqId); printContractDetailsMsg(contractDetails); }
public virtual void contractDetails(int reqId, ContractDetails contractDetails) { Console.WriteLine("ContractDetails. ReqId: " + reqId); printContractDetailsMsg(contractDetails); }
Public Sub contractDetails(reqId As Integer, contractDetails As IBApi.ContractDetails) Implements IBApi.EWrapper.contractDetails Console.WriteLine("ContractDetails. ReqId: " & reqId) printContractDetailsMsg(contractDetails) End Sub
EWrapper.contractDetailsEnd (
reqId: int. Request identifier to track data.
)
After all contracts matching the request were returned, this method will mark the end of their reception.
def contractDetailsEnd(self, reqId: int): print("ContractDetailsEnd. ReqId:", reqId)
@Override public void contractDetailsEnd(int reqId) { System.out.println("Contract Details End: " + EWrapperMsgGenerator.contractDetailsEnd(reqId)); }
void TestCppClient::contractDetailsEnd( int reqId) { printf( "ContractDetailsEnd. %dn", reqId); }
public virtual void contractDetailsEnd(int reqId) { Console.WriteLine("ContractDetailsEnd. "+reqId+"n"); }
Public Sub contractDetailsEnd(reqId As Integer) Implements IBApi.EWrapper.contractDetailsEnd Console.WriteLine("ContractDetailsEnd - ReqId [" & reqId & "]") End Sub
Receive Bond Details Copy Location
Copy Location
EWrapper.bondContractDetails (
reqId: int. Request identifier to track data.
contract: ContractDetails. Contains the full contract object contents including all information about a specific traded instrument.
)
Delivers the Bond contract data after this has been requested via reqContractDetails.
def bondContractDetails(self, reqId: int, contractDetails: ContractDetails): printinstance(reqId, contractDetails)
@Override public void bondContractDetails(int reqId, ContractDetails contractDetails) { System.out.println(EWrapperMsgGenerator.contractDetails(reqId, contractDetails)); }
void TestCppClient::bondContractDetails( int reqId, const ContractDetails& contractDetails) { printf( "BondContractDetails. ReqId: %dn", reqId); printContractDetailsMsg(contractDetails); }
public virtual void bondContractDetails(int reqId, ContractDetails contractDetails) { Console.WriteLine("BondContractDetails. ReqId: " + reqId); printContractDetailsMsg(contractDetails); }
Public Sub bondContractDetails(reqId As Integer, contractDetails As IBApi.ContractDetails) Implements IBApi.EWrapper.contractDetails Console.WriteLine("BondContractDetails. ReqId: " & reqId) printContractDetailsMsg(contractDetails) End Sub
Option Chains Copy Location
Copy Location
The option chain for a given security can be returned using the function reqContractDetails. If an option contract is incompletely defined (for instance with the strike undefined) and used as an argument to IBApi::EClient::reqContractDetails, a list of all matching option contracts will be returned.
One limitation of this technique is that the return of option chains will be throttled and take a longer time the more ambiguous the contract definition.The function IBApi::EClient::reqSecDefOptParams was introduced that does not have the throttling limitation.
- It is not recommended to use reqContractDetails to receive complete option chains on an underlying, e.g. all combinations of strikes/rights/expiries.
- For very large option chains returned from reqContractDetails, unchecking the setting in TWS Global Configuration at API -> Settings -> “Expose entire trading schedule to the API” will decrease the amount of data returned per option and help to return the contract list more quickly.
IBApi::EClient::reqSecDefOptParams returns a list of expiries and a list of strike prices. In some cases it is possible there are combinations of strike and expiry that would not give a valid option contract.
Request Option Chains Copy Location
Copy Location
EClient.reqSecDefOptParams (
reqId: int. The ID chosen for the request
underlyingSymbol: String. Contract symbol of the underlying.
futFopExchange: String. The exchange on which the returned options are trading. Can be set to the empty string “” for all exchanges.
underlyingSecType: String. The type of the underlying security, i.e. STK
underlyingConId: int. The contract ID of the underlying security.
)
Requests security definition option parameters for viewing a contract’s option chain.
self.reqSecDefOptParams(0, "IBM", "", "STK", 8314)
client.reqSecDefOptParams(0, "IBM", "", "STK", 8314);
m_pClient->reqSecDefOptParams(0, "IBM", "", "STK", 8314);
client.reqSecDefOptParams(0, "IBM", "", "STK", 8314);
client.reqSecDefOptParams(0, "IBM", "", "STK", 8314)
Receive Option Chains Copy Location
Copy Location
EWrapper.securityDefinitionOptionParameter (
reqId: int. ID of the request initiating the callback.
underlyingConId: int. The conID of the underlying security.
tradingClass: String. The option trading class.
multiplier: String. The option multiplier.
exchange: String. Exchange for which the derivative is hosted.
expirations: HashSet. A list of the expiries for the options of this underlying on this exchange.
strikes: HashSet. A list of the possible strikes for options of this underlying on this exchange.
)
Returns the option chain for an underlying on an exchange specified in reqSecDefOptParams There will be multiple callbacks to securityDefinitionOptionParameter if multiple exchanges are specified in reqSecDefOptParams
def securityDefinitionOptionParameter(self, reqId: int, exchange: str, underlyingConId: int, tradingClass: str, multiplier: str, expirations: SetOfString, strikes: SetOfFloat): print("SecurityDefinitionOptionParameter.", "ReqId:", reqId, "Exchange:", exchange, "Underlying conId:", underlyingConId, "TradingClass:", tradingClass, "Multiplier:", multiplier, "Expirations:", expirations, "Strikes:", strikes)
@Override public void securityDefinitionOptionalParameter(int reqId, String exchange, int underlyingConId, String tradingClass, String multiplier, Set expirations, Set strikes) { System.out.println("Security Definition Optional Parameter: " + EWrapperMsgGenerator.securityDefinitionOptionalParameter(reqId, exchange, underlyingConId, tradingClass, multiplier, expirations, strikes)); }
void TestCppClient::securityDefinitionOptionalParameter(int reqId, const std::string& exchange, int underlyingConId, const std::string& tradingClass, const std::string& multiplier, const std::set& expirations, const std::set& strikes) { printf("Security Definition Optional Parameter. Request: %d, Trading Class: %s, Multiplier: %sn", reqId, tradingClass.c_str(), multiplier.c_str()); }
public void securityDefinitionOptionParameter(int reqId, string exchange, int underlyingConId, string tradingClass, string multiplier, HashSet expirations, HashSet strikes) { Console.WriteLine("Security Definition Option Parameter. Reqest: {0}, Exchange: {1}, Undrelying contract id: {2}, Trading class: {3}, Multiplier: {4}, Expirations: {5}, Strikes: {6}", reqId, exchange, Util.IntMaxString(underlyingConId), tradingClass, multiplier, string.Join(", ", expirations), string.Join(", ", strikes)); }
Public Sub securityDefinitionOptionParameter(reqId As Integer, exchange As String, underlyingConId As Integer, tradingClass As String, multiplier As String, expirations As HashSet(Of String), strikes As HashSet(Of Double)) Implements EWrapper.securityDefinitionOptionParameter Console.WriteLine("securityDefinitionOptionParameter: " & reqId & " tradingClass: " & tradingClass & " multiplier: ") End Sub
Stock Symbol Search Copy Location
Copy Location
The function IBApi::EClient::reqMatchingSymbols is available to search for stock contracts. The input can be either the first few letters of the ticker symbol, or for longer strings, a character sequence matching a word in the security name. For instance to search for the stock symbol ‘IBKR’, the input ‘I’ or ‘IB’ can be used, as well as the word ‘Interactive’. Up to 16 matching results are returned.
There must be an interval of at least 1 second between successive calls to reqMatchingSymbols
Matching stock contracts are returned to IBApi::EWrapper::symbolSamples with information about types of derivative contracts which exist (warrants, options, dutch warrants, futures).
Request Stock Contract Search Copy Location
Copy Location
EClient.reqMatchingSymbols (
reqId: int. Request identifier used to track data.
pattern: String. Either start of ticker symbol or (for larger strings) company name.
)
Requests matching stock symbols.
self.reqMatchingSymbols(reqId, "IBM")
client.reqMatchingSymbols(reqId, "IB");
m_pClient->reqMatchingSymbols(reqId, "IBM");
client.reqMatchingSymbols(reqId, "IBM");
client.reqMatchingSymbols(reqId, "IBM")
Receive Searched Stock Contract Copy Location
Copy Location
EWrapper.symbolSamples (
reqID: int. Request identifier used to track data.
contractDescription: ContractDescription[]. Provide an array of contract objects matching the requested descriptoin.
)
Returns array of sample contract descriptions
def symbolSamples(self, reqId: int, contractDescriptions: ListOfContractDescription): print("Symbol Samples. Request Id: ", reqId) for contractDescription in contractDescriptions: derivSecTypes = "" for derivSecType in contractDescription.derivativeSecTypes: derivSecTypes += " " derivSecTypes += derivSecType print("Contract: conId:%s, symbol:%s, secType:%s primExchange:%s, " "currency:%s, derivativeSecTypes:%s, description:%s, issuerId:%s" % ( contractDescription.contract.conId, contractDescription.contract.symbol, contractDescription.contract.secType, contractDescription.contract.primaryExchange, contractDescription.contract.currency, derivSecTypes, contractDescription.contract.description, contractDescription.contract.issuerId))
@Override public void symbolSamples(int reqId, ContractDescription[] contractDescriptions) { System.out.println(EWrapperMsgGenerator.symbolSamples(reqId, contractDescriptions)); }
void TestCppClient::symbolSamples(int reqId, const std::vector &contractDescriptions) { printf("Symbol Samples (total=%lu) reqId: %dn", contractDescriptions.size(), reqId); for (unsigned int i = 0; i < contractDescriptions.size(); i++) { Contract contract = contractDescriptions[i].contract; std::vector derivativeSecTypes = contractDescriptions[i].derivativeSecTypes; printf("Contract (%u): conId: %ld, symbol: %s, secType: %s, primaryExchange: %s, currency: %s, ", i, contract.conId, contract.symbol.c_str(), contract.secType.c_str(), contract.primaryExchange.c_str(), contract.currency.c_str()); printf("Derivative Sec-types (%lu):", derivativeSecTypes.size()); for (unsigned int j = 0; j < derivativeSecTypes.size(); j++) { printf(" %s", derivativeSecTypes[j].c_str()); } printf(", description: %s, issuerId: %s", contract.description.c_str(), contract.issuerId.c_str()); printf("n"); } }
public void symbolSamples(int reqId, ContractDescription[] contractDescriptions) { string derivSecTypes; Console.WriteLine("Symbol Samples. Request Id: {0}", reqId); foreach (var contractDescription in contractDescriptions) { derivSecTypes = ""; foreach (var derivSecType in contractDescription.DerivativeSecTypes) { derivSecTypes += derivSecType; derivSecTypes += " "; } Console.WriteLine("Contract: conId - {0}, symbol - {1}, secType - {2}, primExchange - {3}, currency - {4}, derivativeSecTypes - {5}, description - {6}, issuerId - {7}", contractDescription.Contract.ConId, contractDescription.Contract.Symbol, contractDescription.Contract.SecType, contractDescription.Contract.PrimaryExch, contractDescription.Contract.Currency, derivSecTypes, contractDescription.Contract.Description, contractDescription.Contract.IssuerId); } }
Public Sub symbolSamples(reqId As Integer, contractDescriptions As ContractDescription()) Implements EWrapper.symbolSamples Dim derivSecTypes As String Console.WriteLine("Symbol Samples. Request Id: " & reqId) For Each contractDescription In contractDescriptions derivSecTypes = "" For Each derivSecType In contractDescription.DerivativeSecTypes derivSecTypes += derivSecType derivSecTypes += " " Next Console.WriteLine("Contract conId: " & contractDescription.Contract.ConId & ", symbol: " & contractDescription.Contract.Symbol & ", secType: " & contractDescription.Contract.SecType & ", primExchange: " & contractDescription.Contract.PrimaryExch & ", currency: " & contractDescription.Contract.Currency & ", derivativeSecTypes: " & derivSecTypes & ", description: " & contractDescription.Contract.Description & ", issuerId: " & contractDescription.Contract.IssuerId) Next End Sub
Error Handling Copy Location
Copy Location
When a client application sends a message to TWS which requires a response which has an expected response (i.e. placing an order, requesting market data, subscribing to account updates, etc.), TWS will almost either always 1) respond with the relevant data or 2) send an error message to IBApi::EWrapper::error.
- Exceptions when no response can occur: Also, if a request is made prior to full establishment of connection (denoted by a returned 2104 or 2106 error code “Data Server is Ok”), there may not be a response from the request.
Error messages sent by the TWS are handled by the IBApi.EWrapper.error method. The IBApi.EWrapper.error event contains the originating request Id (or the orderId in case the error was raised when placing an order), a numeric error code and a brief description. It is important to keep in mind that this function is used for true error messages as well as notifications that do not mean anything is wrong.
API Error Messages when TWS is not set to the English Language
- Currently on the Windows platform, error messages are sent using Latin1 encoding. If TWS is launched in a non-Western language, it is recommended to enable the setting at Global Configuration -> API -> Settings to “Show API error messages in English”.
Advanced order rejection Copy Location
Copy Location
Order advancedErrorOverride and EWrapper.error advancedOrderRejectJson properties.
- advancedErrorOverride accepts a comma-separated list with parameters containing error tags. This list will override the mentioned errors and proceed with the order placement.
- advancedOrderRejectJson returns order reject description in JSON format. The JSON responses can be used to add fields to advancedErrorOverride.
The response your API client will receive from our back end via reject message will contain a FIX Tag 8230. This FIX Tag is for order rejection message.
For example, the response will contain code 8229=IBDBUYTX which can be passed in 8229 (advancedErrorOverride) field in IBApi::EClient::placeOrder method.
The tag values of 8229 can contain a comma-separated list of advanced error override codes. For example, 8229=IBDBUYTX,MOBILEPH, will override both of the rejections. - Additionally, a new API Setting has been introduced: Show advanced order reject in UI always
If checked, the order reject will not be sent to API.
Error Message Codes Copy Location
Copy Location
For a full list of all available error codes from the TWS API, please visit our TWS API Error Messages page.
Receive Error Messages Copy Location
Copy Location
EWrapper.error(
reqId: int. The request identifier which generated the error. Note: -1 will indicate a notification and not true error condition.
errorCode: int. The code identifying the error.
errorMsg: String. The error’s description.
advancedOrderRejectJson: String. Advanced order reject description in json format.
)
See the TWS Error Codes section for more details on specific error messages.
def error(self, reqId: TickerId, errorCode: int, errorString: str, advancedOrderRejectJson = ""): print("Error. Id:", reqId, "Code:", errorCode, "Msg:", errorString, "AdvancedOrderRejectJson:", advancedOrderRejectJson)
@Override public void error(int id, int errorCode, String errorMsg, String advancedOrderRejectJson) { String str = "Error. Id: " + id + ", Code: " + errorCode + ", Msg: " + errorMsg; if (advancedOrderRejectJson != null) { str += (", AdvancedOrderRejectJson: " + advancedOrderRejectJson); } System.out.println(str + "n"); }
void TestCppClient::error(int id, int errorCode, const std::string& errorString, const std::string& advancedOrderRejectJson) { printf("Error. Id: %d, Code: %d, Msg: %s, AdvancedOrderRejectJson: %sn", id, errorCode, errorString.c_str(), advancedOrderRejectJson.c_str()); }
public virtual void error(int id, int errorCode, string errorMsg, string advancedOrderRejectJson) { Console.WriteLine("Error. Id: " + id + ", Code: " + errorCode + ", Msg: " + errorMsg + ", AdvancedOrderRejectJson: " + advancedOrderRejectJson + "n"); }
Public Sub [error](id As Integer, errorCode As Integer, errorMsg As String, advancedOrderRejectJson As String) Implements IBApi.EWrapper.error Console.WriteLine("Error - Id [" & id & "] ErrorCode [" & errorCode & "] ErrorMsg [" & errorMsg & "] AdvancedOrderRejectJson [" & advancedOrderRejectJson & "]") End Sub
Financial Advisors Copy Location
Copy Location
Allocation Methods and Groups Copy Location
Copy Location
A number of methods and profiles are available with Financial Advisor and IBroker account structures to specify how trades should be distributed across multiple accounts. This functionality allows for trades to be placed across multiple accounts. The API has the same functionality available as TWS.
Group and Profile order allocation methods for Financial Advisor Accounts can be created directly in TWS: Allocations and Transfers. After the initial creation, modifications can be made through the IBApi.EClient.replaceFA() method via the API directly.
As suggested from the method names below, a Group will distribute the order based on inherent properties such as the account’s liquidation value or equity whereas a Profile will offer the possibility to assign the allocated proportion based on explicit ratios or percentages.
Note: There is an API setting which merges groups and profiles, where both allocation methods are considered groups. See Unification of Groups and Profiles
Allocation by Group Copy Location
Copy Location
EqualQuantity
Requires you to specify an order size. This method distributes shares equally between all accounts in the group.
Example: You transmit an order for 400 shares of stock ABC. If your Account Group includes four accounts, each account receives 100 shares. If your Account Group includes six accounts, each account receives 66 shares, and then 1 share is allocated to each account until all are distributed.
NetLiq
Requires you to specify an order size. This method distributes shares based on the net liquidation value of each account. The system calculates ratios based on the Net Liquidation value in each account and allocates shares based on these ratios.
Example: You transmit an order for 700 shares of stock XYZ. The account group includes three accounts, A, B and C with Net Liquidation values of $25,000, $50,000 and $100,000 respectively. The system calculates a ratio of 1:2:4 and allocates 100 shares to Client A, 200 shares to Client B, and 400 shares to Client C.
AvailableEquity
Requires you to specify an order size. This method distributes shares based on the amount of available equity in each account. The system calculates ratios based on the Available Equity in each account and allocates shares based on these ratios.
Example: You transmit an order for 700 shares of stock XYZ. The account group includes three accounts, A, B and C with available equity in the amounts of $25,000, $50,000 and $100,000 respectively. The system calculates a ratio of 1:2:4 and allocates 100 shares to Client A, 200 shares to Client B, and 400 shares to Client C.
PctChange
Do not specify an order size. Since the quantity is calculated by the system, the order size is displayed in the Quantity field after the order is acknowledged. This method increases or decreases an already existing position. Positive percents will increase a position, negative percents will decrease a position. For exmaple, to fully close out a position, you just need to specify percentage to be -100.
BUY ORDER | Positive Percent | Negative Percent |
---|---|---|
Long Position | Increases position | No effect |
Short Position | No effect | Decreases position |
SELL ORDER | Positive Percent | Negative Percent |
---|---|---|
Long Position | No effect | Decreases position |
Short Position | Increases position | No effect |
Allocation by Profile Copy Location
Copy Location
While making modifications to allocations for profiles, the method uses an enumerated value. The number on the right demonstrates precisely what profile corresponds to which value.
Profile Methods | Type Number |
---|---|
Percentages | 1 |
Financial Ratios | 2 |
Shares | 3 |
Percentages
This method will split the total number of shares in the order between listed accounts based on the percentages you indicate. For example, an order for 1000 shares using a profile with four accounts at 25% each would allocate 250 shares to each listed account in the profile.
Financial Ratios
This method calculates the allocation of shares based on the ratios you enter. For example, an order for 1000 shares using a profile with four accounts set to a ratio of 4, 2, 1, 1 would allocate 500, 250, 125 and 125 shares to the listed accounts, respectively.
Shares
This method allocates the absolute number of shares you enter to each account listed. If you use this method, the order size is calculated by adding together the number of shares allocated to each account in the profile.
Managing Groups and Profiles from the API Copy Location
Copy Location
Customers are able to manage their existing allocation groups from the TWS API.
Important: While the API is able to modify these groups and profiles, the API is unable to create them. See the TWS Allocations and Transfers section of our guides for more information.
Note: Modifications made through the API will effect orders placed through TWS, the TWS API, Client Portal, and the Client Portal API.
Request FA Groups and Profiles Copy Location
Copy Location
EClient.requestFA (
faDataType: int. The configuration to change. Set to 1 or 3 as defined in the table below.
)
Requests the FA configuration as set in TWS for the given FA Group or Profile.
self.requestFA(1)
client.requestFA(1);
m_pClient->requestFA(1);
client.requestFA(1);
client.requestFA(1)
FA Data Types Copy Location
Copy Location
Type Code | Type Name | Description |
---|---|---|
1 | Groups | offer traders a way to create a group of accounts and apply a single allocation method to all accounts in the group. |
3 | Account Aliases | let you easily identify the accounts by meaningful names rather than account numbers. |
Receiving FA Groups and Profiles Copy Location
Copy Location
EWrapper.receiveFA (
faDataType: int. Receive the faDataType value specified in the requestFA. See FA Data Types
faXmlData: String. The xml-formatted configuration.
)
Receives the Financial Advisor’s configuration available in the TWS.
def receiveFA(self, faData: FaDataType, cxml: str): print("Receiving FA: ", faData) open('log/fa.xml', 'w').write(cxml)
@Override public void receiveFA(int faDataType, String xml) { System.out.println("Receiving FA: " + faDataType + " - " + xml); }
void TestCppClient::receiveFA(faDataType pFaDataType, const std::string& cxml) { std::cout << "Receiving FA: " << (int)pFaDataType << std::endl << cxml << std::endl; }
public virtual void receiveFA(int faDataType, string faXmlData) { Console.WriteLine("Receing FA: "+faDataType+" - "+faXmlData); }
Public Sub receiveFA(faDataType As Integer, faXmlData As String) Implements IBApi.EWrapper.receiveFA Console.WriteLine("Receing FA: " & faDataType & " - " & faXmlData) End Sub
Replace FA Allocations Copy Location
Copy Location
EClient.replaceFA (
reqId: int. Request identifier used to track data.
faDataType: int. The configuration structure to change. See FA Data Types
xml: String. XML configuration for allocation profiles or group. See ReplaceFA XML Structure for more details.
)
self.replaceFa(reqId, 1, xml)
client.replaceFa(reqId, 1, xml);
m_pClient->replaceFa(reqId, 1, xml);
client.replaceFa(reqId, 1, xml);
client.replaceFa(reqId, 1, xml)
ReplaceFA XML Structure Copy Location
Copy Location
The structure on the right is a generic structure for allocations. However, for the most accurate results, we recommend initially calling the EClient.requestFa method in order to confirm existing information before modification.
<?xml version="1.0" encoding="UTF-8"?> <ListOfGroups> <Group> <name>Profile_Name</name> <defaultMethod>Allocation_Method</defaultMethod> <ListOfAccts varName="list"> <Account> <acct>Account_n</acct> <amount>Amount</amount> </Account> <Account> <acct>Account_n+1</acct> <amount>Amount</amount> </Account> </ListOfAccts> </Group> </ListOfGroups>
Model Portfolios and the API Copy Location
Copy Location
Advisors can use Model Portfolios to easily invest some or all of a client’s assets into one or multiple custom-created portfolios, rather than tediously managing individual investments in single instruments.
The TWS API can access model portfolios in accounts where this functionality is available and a specific model has previously been setup in TWS. API functionality allows the client application to request model position update subscriptions, request model account update subscriptions, or place orders to a specific model.
Model Portfolio functionality not available in the TWS API:
- Portfolio Model Creation
- Portfolio Model Rebalancing
- Portfolio Model Position or Cash Transfer
To request position updates from a specific model, the function IBApi::EClient::reqPositionsMulti can be used: Position Update Subscription by Model
To request model account updates, there is the function IBApi::EClient::reqAccountUpdatesMulti, see: Account Value Update Subscriptions by Model
To place an order to a model, the IBApi.Order.ModelCode field must be set accordingly, for example:
modelOrder = Order() modelOrder.account = "DF12345" modelOrder.modelCode = "Technology" # model for tech stocks first created in TWS self.placeOrder(self.nextOrderId(), contract, modelOrder)
Order modelOrder = Order(); modelOrder.account("DF12345"); // master FA account number modelOrder.modelCode("Technology"); // model for tech stocks first created in TWS client.placeOrder(nextOrderId++, contract, modelOrder);
Order modelOrder = Order(); modelOrder.account = "DF12345"; modelOrder.modelCode = "Technology"; m_pClient->placeOrder(m_orderId++, contract, modelOrder);
Order modelOrder = Order(); modelOrder.Account = "DF12345"; // master FA account number modelOrder.ModelCode = "Technology"; // model for tech stocks first created in TWS client.placeOrder(nextOrderId++, contract, modelOrder);
Dim modelOrder As Order = Order() modelOrder.Account = "DF12345" 'master FA account number modelOrder.ModelCode = "Technology" 'model for tech stocks first created in TWS client.placeOrder(increment(nextOrderId), contract, modelOrder)
Unification of Groups and Profiles Copy Location
Copy Location
With TWS/IBGW build 983+, the API settings will have a new flag/checkbox, “Use Account Groups with Allocation Methods” (enabled by default for new users). If not enabled, groups and profiles would behave the same as before. If it is checked, group and profile functionality will be merged, and API clients will see the following changes:
- Both IBApi::EClient::replaceFA and IBApi::EClient::requestFA will send and receive unified groups/profiles list if the argument is Group.
- Both IBApi::EClient::replaceFA and IBApi::EClient::requestFA will receive error if the argument is Profile.
- IBApi::EClient::placeOrder will support specifying profile name as the IBApi.Order.FaGroup name; IBApi::Order::FaMethod may be omitted.
- If specifying actual group name and the faMethod is blank/omitted the default method of that group will be used. Otherwise, the method in the request will be set on the order.
- IBApi::EWrapper::openOrder callback will report Profile in place of Group if order was for profile.
- The following calls from API, which take Group name, will also accept Profile name in its place:
Placing Orders to a FA account