Skip to navigation

Account Updates

View as MarkdownOpen in Claude

Introduction

The EClient.reqAccountUpdates function creates a subscription to the TWS through which account and portfolio information is delivered. This information is the exact same as the one displayed within the TWS’ Account Window. Just as with the TWS’ Account Window, unless there is a position change this information is updated at a fixed interval of three minutes.

Unrealized and Realized P&L is sent to the API function EWrapper.updateAccountValue after a subscription request is made with EClient.reqAccountUpdates. This information corresponds to the data in the TWS Account Window, and has a different source of information, a different update frequency, and different reset schedule than PnL data in the TWS Portfolio Window and associated API functions. In particular, the unrealized P&L information shown in the TWS Account Window which is sent to EWrapper.updatePortfolio will update either (1) when a trade for that particular instrument occurs or (2) every 3 minutes. The realized P&L data in the TWS Account Window is reset to 0 once per day.

It is important to keep in mind that the P&L data shown in the Account Window and Portfolio Window will sometimes differ because there is a different source of information and a different reset schedule.

See Profit & Loss for alternative PnL data.


Requesting Account Updates

EClient.reqAccountUpdates(subscribe, acctCode)

Subscribes to a specific account’s information and portfolio. Through this method, a single account’s subscription can be started/stopped. As a result from the subscription, the account’s information, portfolio and last update time will be received at EWrapper.updateAccountValue, EWrapper.updatePortfolio, and EWrapper.updateAccountTime respectively. All account values and positions will be returned initially, and then there will only be updates when there is a change in a position, or to an account value every 3 minutes if it has changed. Only one account can be subscribed at a time. A second subscription request for another account when the previous one is still active will cause the first one to be canceled in favor of the second one.

subscribe
bool

Set to true to start the subscription and to false to stop it.

acctCode
string

The account id (i.e. U123456) for which the information is requested.


self.reqAccountUpdates(True, self.account)

Account Value Keys

When requesting reqAccountUpdates, customers will receive values corresponding to various account key/value pairs. Account values delivered via EWrapper.updateAccountValue can be classified in the following way:

  • Commodities: suffixed by a -C
  • Securities: suffixed by a -S
  • Totals: no suffix
KeyDescription
AccountCodeThe account ID number
AccountOrGroup”All” to return account summary data for all accounts, or set to a specific Advisor Account Group name that has already been created in TWS Global Configuration
AccountReadyIf an accountReady value of false is returned that means that the IB server is in the process of resetting at that moment, i.e. the account is ‘not ready’. When this occurs subsequent key values returned to EWrapper.updateAccountValue in the current update can be out of date or incorrect.
AccountTypeIdentifies the IB account structure
AccruedCashTotal accrued cash value of stock, commodities and securities
AccruedCash-CReflects the current’s month accrued debit and credit interest to date, updated daily in commodity segment
AccruedCash-SReflects the current’s month accrued debit and credit interest to date, updated daily in security segment
AccruedDividendTotal portfolio value of dividends accrued
AccruedDividend-CDividends accrued but not paid in commodity segment
AccruedDividend-SDividends accrued but not paid in security segment
AvailableFundsThis value tells what you have available for trading
AvailableFunds-CNet Liquidation Value – Initial Margin
AvailableFunds-SEquity with Loan Value – Initial Margin
BillableTotal portfolio value of treasury bills
Billable-CValue of treasury bills in commodity segment
Billable-SValue of treasury bills in security segment
BuyingPowerCash Account: Minimum (Equity with Loan Value, Previous Day Equity with Loan Value)-Initial Margin, Standard Margin Account: Minimum (Equity with Loan Value, Previous Day Equity with Loan Value) – Initial Margin *4
CashBalanceCash recognized at the time of trade + futures PNL
CorporateBondValueValue of non-Government bonds such as corporate bonds and municipal bonds
CurrencyOpen positions are grouped by currency
CushionExcess liquidity as a percentage of net liquidation value
DayTradesRemainingNumber of Open/Close trades one could do before Pattern Day Trading is detected
DayTradesRemainingT+1Number of Open/Close trades one could do tomorrow before Pattern Day Trading is detected
DayTradesRemainingT+2Number of Open/Close trades one could do two days from today before Pattern Day Trading is detected
DayTradesRemainingT+3Number of Open/Close trades one could do three days from today before Pattern Day Trading is detected
DayTradesRemainingT+4Number of Open/Close trades one could do four days from today before Pattern Day Trading is detected
EquityWithLoanValueForms the basis for determining whether a client has the necessary assets to either initiate or maintain security positions
EquityWithLoanValue-CCash account: Total cash value + commodities option value – futures maintenance margin requirement + minimum (0, futures PNL) Margin account: Total cash value + commodities option value – futures maintenance margin requirement
EquityWithLoanValue-SCash account: Settled Cash Margin Account: Total cash value + stock value + bond value + (non-U.S. & Canada securities options value)
ExcessLiquidityThis value shows your margin cushion, before liquidation
ExcessLiquidity-CEquity with Loan Value – Maintenance Margin
ExcessLiquidity-SNet Liquidation Value – Maintenance Margin
ExchangeRateThe exchange rate of the currency to your base currency
FullAvailableFundsAvailable funds of whole portfolio with no discounts or intraday credits
FullAvailableFunds-CNet Liquidation Value – Full Initial Margin
FullAvailableFunds-SEquity with Loan Value – Full Initial Margin
FullExcessLiquidityExcess liquidity of whole portfolio with no discounts or intraday credits
FullExcessLiquidity-CNet Liquidation Value – Full Maintenance Margin
FullExcessLiquidity-SEquity with Loan Value – Full Maintenance Margin
FullInitMarginReqInitial Margin of whole portfolio with no discounts or intraday credits
FullInitMarginReq-CInitial Margin of commodity segment’s portfolio with no discounts or intraday credits
FullInitMarginReq-SInitial Margin of security segment’s portfolio with no discounts or intraday credits
FullMaintMarginReqMaintenance Margin of whole portfolio with no discounts or intraday credits
FullMaintMarginReq-CMaintenance Margin of commodity segment’s portfolio with no discounts or intraday credits
FullMaintMarginReq-SMaintenance Margin of security segment’s portfolio with no discounts or intraday credits
FundValueValue of funds value (money market funds + mutual funds)
FutureOptionValueReal-time market-to-market value of futures options
FuturesPNLReal-time changes in futures value since last settlement
FxCashBalanceCash balance in related IB-UKL account
GrossPositionValueGross Position Value in securities segment
GrossPositionValue-SLong Stock Value + Short Stock Value + Long Option Value + Short Option Value
IndianStockHaircutMargin rule for IB-IN accounts
InitMarginReqInitial Margin requirement of whole portfolio
InitMarginReq-CInitial Margin of the commodity segment in base currency
InitMarginReq-SInitial Margin of the security segment in base currency
IssuerOptionValueReal-time mark-to-market value of Issued Option
Leverage-SGrossPositionValue / NetLiquidation in security segment
LookAheadNextChangeTime when look-ahead values take effect
LookAheadAvailableFundsThis value reflects your available funds at the next margin change
LookAheadAvailableFunds-CNet Liquidation Value – look ahead Initial Margin
LookAheadAvailableFunds-SEquity with Loan Value – look ahead Initial Margin
LookAheadExcessLiquidityThis value reflects your excess liquidity at the next margin change
LookAheadExcessLiquidity-CNet Liquidation Value – look ahead Maintenance Margin
LookAheadExcessLiquidity-SEquity with Loan Value – look ahead Maintenance Margin
LookAheadInitMarginReqInitial margin requirement of whole portfolio as of next period’s margin change
LookAheadInitMarginReq-CInitial margin requirement as of next period’s margin change in the base currency of the account
LookAheadInitMarginReq-SInitial margin requirement as of next period’s margin change in the base currency of the account
LookAheadMaintMarginReqMaintenance margin requirement of whole portfolio as of next period’s margin change
LookAheadMaintMarginReq-CMaintenance margin requirement as of next period’s margin change in the base currency of the account
LookAheadMaintMarginReq-SMaintenance margin requirement as of next period’s margin change in the base currency of the account
MaintMarginReqMaintenance Margin requirement of whole portfolio
MaintMarginReq-CMaintenance Margin for the commodity segment
MaintMarginReq-SMaintenance Margin for the security segment
MoneyMarketFundValueMarket value of money market funds excluding mutual funds
MutualFundValueMarket value of mutual funds excluding money market funds
NetDividendThe sum of the Dividend Payable/Receivable Values for the securities and commodities segments of the account
NetLiquidationThe basis for determining the price of the assets in your account
NetLiquidation-CTotal cash value + futures PNL + commodities options value
NetLiquidation-STotal cash value + stock value + securities options value + bond value
NetLiquidationByCurrencyNet liquidation for individual currencies
OptionMarketValueReal-time mark-to-market value of options
PASharesValuePersonal Account shares value of whole portfolio
PASharesValue-CPersonal Account shares value in commodity segment
PASharesValue-SPersonal Account shares value in security segment
PostExpirationExcessTotal projected “at expiration” excess liquidity
PostExpirationExcess-CProvides a projected “at expiration” excess liquidity based on the soon-to expire contracts in your portfolio in commodity segment
PostExpirationExcess-SProvides a projected “at expiration” excess liquidity based on the soon-to expire contracts in your portfolio in security segment
PostExpirationMarginTotal projected “at expiration” margin
PostExpirationMargin-CProvides a projected “at expiration” margin value based on the soon-to expire contracts in your portfolio in commodity segment
PostExpirationMargin-SProvides a projected “at expiration” margin value based on the soon-to expire contracts in your portfolio in security segment
PreviousDayEquityWithLoanValueMarginable Equity with Loan value as of 16:00 ET the previous day in securities segment
PreviousDayEquityWithLoanValue-SIMarginable Equity with Loan value as of 16:00 ET the previous day
RealCurrencyOpen positions are grouped by currency
RealizedPnLShows your profit on closed positions, which is the difference between your entry execution cost and exit execution costs, or (execution price + commissions to open the positions) – (execution price + commissions to close the position)
RegTEquityRegulation T equity for universal account
RegTEquity-SRegulation T equity for security segment
RegTMarginRegulation T margin for universal account
RegTMargin-SRegulation T margin for security segment
SMALine of credit created when the market value of securities in a Regulation T account increase in value
SMA-SRegulation T Special Memorandum Account balance for security segment
SegmentTitleAccount segment name
StockMarketValueReal-time mark-to-market value of stock
TBondValueValue of treasury bonds
TBillValueValue of treasury bills
TotalCashBalanceTotal Cash Balance including Future PNL
TotalCashValueTotal cash value of stock, commodities and securities
TotalCashValue-CCashBalance in commodity segment
TotalCashValue-SCashBalance in security segment
TradingType-SAccount Type
UnrealizedPnLThe difference between the current market value of your open positions and the average cost, or Value – Average Cost
WarrantValueValue of warrants
WhatIfPMEnabledTo check projected margin requirements under Portfolio Margin model

Receiving Account Updates

Resulting account and portfolio information will be delivered via EWrapper.updateAccountValue, EWrapper.updatePortfolio, EWrapper.updateAccountTime, and EWrapper.accountDownloadEnd.

EWrapper.updateAccountValue

EWrapper.updateAccountValue(key, value, currency, accountName)

Receives the subscribed account’s information. Only one account can be subscribed at a time. After the initial callback to updateAccountValue, callbacks only occur for values which have changed. This occurs at the time of a position change, or every 3 minutes at most. This frequency cannot be adjusted.

An important key passed back in EWrapper.updateAccountValue after a call to EClient.reqAccountUpdates is a boolean value ‘accountReady’. If an accountReady value of false is returned that means that the IB server is in the process of resetting at that moment. When this occurs subsequent key values returned to EWrapper.updateAccountValue in the current update can be out of date or incorrect.
key
string

The value being updated.

value
string

Up-to-date value.

currency
string

The currency on which the value is expressed.

accountName
string

The account identifier.


def updateAccountValue(self, key: str, val: str, currency: str,accountName: str):
print("UpdateAccountValue. Key:", key, "Value:", val, "Currency:", currency, "AccountName:", accountName)

EWrapper.updatePortfolio

EWrapper.updatePortfolio(contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName)

Receives the subscribed account’s portfolio. This function will receive only the portfolio of the subscribed account. After the initial callback to updatePortfolio, callbacks only occur for positions which have changed.

contract
Contract

The Contract for which a position is held.

position
decimal

The number of positions held.

marketPrice
double

The instrument’s unitary price.

marketValue
double

Total market value of the instrument.

averageCost
double

Average cost of the overall position.

unrealizedPNL
double

Daily unrealized profit and loss on the position.

realizedPNL
double

Daily realized profit and loss on the position.

accountName
string

Account ID for the update.


def updatePortfolio(self, contract: Contract, position: Decimal,marketPrice: float, marketValue: float, averageCost: float, unrealizedPNL: float, realizedPNL: float, accountName: str):
print("UpdatePortfolio.", "Symbol:", contract.symbol, "SecType:", contract.secType, "Exchange:",contract.exchange, "Position:", decimalMaxString(position), "MarketPrice:", floatMaxString(marketPrice),"MarketValue:", floatMaxString(marketValue), "AverageCost:", floatMaxString(averageCost), "UnrealizedPNL:", floatMaxString(unrealizedPNL), "RealizedPNL:", floatMaxString(realizedPNL), "AccountName:", accountName)

EWrapper.updateAccountTime

EWrapper.updateAccountTime(timestamp)

Receives the last time on which the account was updated.

timestamp
string

The last update system time.


def updateAccountTime(self, timeStamp: str):
print("UpdateAccountTime. Time:", timeStamp)

EWrapper.accountDownloadEnd

EWrapper.accountDownloadEnd(account)

Notifies when all the account’s information has finished.

account
string

The account identifier.


def accountDownloadEnd(self, accountName: str):
print("AccountDownloadEnd. Account:", accountName)

Cancel Account Updates

EClient.reqAccountUpdates(subscribe, acctCode)

Once the subscription to account updates is no longer needed, it can be cancelled by invoking EClient.reqAccountUpdates with subscribe set to false.

Only one account at a time can be subscribed. Attempting a second subscription without previously cancelling an active one will not yield any error message, but will override the already subscribed account with the new one. With Financial Advisory (FA) account structures there is an alternative way of specifying the account code such that information is returned for ‘All’ sub accounts — this is done by appending the letter ‘A’ to the end of the account number, i.e. reqAccountUpdates(true, "F123456A").
subscribe
bool

Set to false to stop the subscription.

acctCode
string

The account id for which the subscription is being cancelled.


self.reqAccountUpdates(False, self.account)