Tuesday, February 24, 2009

Proof Of Concept 8 of 8c : Account Information

Account information such as account value, margin requirements, cash balance, and current portfolio holdings may be retrieve by calling EClientSocket.reqAccountUpdates(). Data are returned in EWrapper's updateAccountTime(), updateAccountValue(), and updatePortfolio() methods. The code is as follows:

require 'java'
require 'TwsApi.jar'

include_class 'ib.client.EClientSocket'
include_class 'ib.client.Contract'
include_class 'ib.client.AnyWrapper'
include_class 'ib.client.EWrapper'


class TestAccount
include EWrapper #note "class TestMktData < EWrapper" syntax is no longer supported in JRuby 1.0

@mySocket

def initialize
@mySocket = EClientSocket.new(self)
end

def eConnect
@mySocket.eConnect("127.0.0.1", 7496, 0)
end

def requestAccount(subscribe, acct_code)
# --------------------------------
@mySocket.reqAccountUpdates(subscribe,
acct_code)
end

def eDisconnect
@mySocket.eDisconnect
end

def contract_msg(contract)
puts ' contract_msg:'
puts ' conid = ' + contract.m_conId.to_s
puts ' symbol = ' + contract.m_symbol
puts ' secType = ' + contract.m_secType
puts ' expiry = ' + contract.m_expiry.to_s
puts ' strike = ' + contract.m_strike.to_s
puts ' right = ' + contract.m_right
puts ' multiplier = ' + contract.m_multiplier.to_s
puts ' exchange = ' + contract.m_exchange.to_s
puts ' primaryExch = ' + contract.m_primaryExch
puts ' currency = ' + contract.m_currency
puts ' localSymbol = ' + contract.m_localSymbol
end

#///////////////////////////////////////////////////////////////////////
#// Interface methods
#///////////////////////////////////////////////////////////////////////

def tickPrice( ticker_id, field, price, can_auto_execute)
end

def tickSize( ticker_id, field, size)
end

def tickOptionComputation( ticker_id, field, implied_vol,
delta, model_price, pv_dividend)
end

def tickGeneric( ticker_id, tick_type, value)
end

def tickString( ticker_id, tick_type, value)
end

def tickEFP( ticker_id, tick_type, basis_points,
formatted_basis_points, implied_future, hold_days,
future_expiry, dividend_impact, dividends_to_expiry)
end

def orderStatus( order_id, status, filled, remaining,
avg_fill_price, perm_id, parent_id, last_fill_price,
client_id, why_held)
end

def openOrder( order_id, contract, order, order_state)
end

def updateAccountValue( key, value, currency, account_name)
puts 'updateAccountValue: ' + key + ' ' + value + ' ' + currency.to_s + ' ' + account_name
end

def updatePortfolio( contract, position, market_price, market_value,
average_cost, unrealized_pnl, realized_pnl, account_name)
puts 'updatePortfolio: --- '
contract_msg(contract)
puts ' position '+position.to_s + ', mkt price ' + market_price.to_s + ', mkt value ' + market_value.to_s +
', avg cost ' + average_cost.to_s + ', unrealized p/l ' + unrealized_pnl.to_s + ', realized p/l ' + realized_pnl.to_s + ' ' + account_name
end

def updateAccountTime( time_stamp)
puts 'updateAccountTime: ' + time_stamp.to_s
end

def nextValidId( order_id)
end

def contractDetails( req_id, contract_details)
end

def bondContractDetails( req_id, contract_details)
end

def contractDetailsEnd( req_id)
end

def execDetails( order_id, contract, execution)
end

def updateMktDepth( ticker_id, position, operation, side, price, size)
end

def updateMktDepthL2( ticker_id, position, market_maker, operation,
side, price, size)
end

def updateNewsBulletin( msg_id, msgType, message, orig_exchange)
end

def managedAccounts( accounts_list)
end

def receiveFA( fa_data_type, xml)
end

def historicalData( req_id, date, open, high, low,
close, volume, count, pWAP, has_gaps)
end

def scannerParameters( xml)
end

def scannerData( req_id, rank, contract_details, distance,
benchmark, projection, legs_str)
end

def scannerDataEnd( req_id)
end

def realtimeBar( req_id, time, open, high, low, close, volume, wap, count)
end

def currentTime( time)
end

def fundamentalData( req_id, data)
end

# ---------------------------------------------------
# -- methods from AnyWrapper -- must be declared
# ---------------------------------------------------

def connectionClosed()
puts ' [API.connectionClosed] Closed connection with TWS'
end

def error(err_obj_str)
puts ' [API.msg1] ' + err_obj_str if err_obj_str.is_a?(String)
puts ' [API.msg3] ' + err_obj_str.getMessage() if err_obj_str.is_a?(Exception)
end

def error(one, two, str)
puts ' [API.msg2] ' + str + ' {' + one.to_s + ', ' + two.to_s + '}'
end

end

# *********************************************************************************************
# Running the code
# *********************************************************************************************
x = TestAccount.new()
begin
x.eConnect
puts 'connected ...'
x.requestAccount(true, '') # subscribe to Account data
sleep(5)
x.requestAccount(false, '') # unsubscribe to Account data
x.eDisconnect
puts 'disconnected'
rescue Exception => e
puts 'can not connect'
puts 'Exception' + e.message
x.eDisconnect
end

Lines 81-83: updateAccountValue() returns key-pair values of all the different account value types.
Lines 85-91: updatePortfolio() returns each individual equity positions held in the account.
Lines 93-95: updateAccountTime() returns last update time of the account information.

This is a screen shot of my paper trading account's View Account Information in TWS. Information returned from the three interface methods should match what is displayed here.



Run output contains contains various account values, account time, and all positions (GE, RUT March 490 Call option, and SPY). Note I've color coded the output for better visibility.

Server Version:43TWS Time at connection:20090224 12:01:06 ESTconnected ...
[API.msg2] Market data farm connection is OK:usopt {-1, 2104}
[API.msg2] Market data farm connection is OK:usfarm {-1, 2104}
updateAccountValue: AccountCode DU58265 DU58265
updateAccountValue: AccountReady true DU58265
updateAccountValue: AccountType UNIVERSAL DU58265
updateAccountValue: AccruedCash 0.00 BASE DU58265
updateAccountValue: AccruedCash 0.00 USD DU58265
updateAccountValue: AccruedCash-S 0.00 USD DU58265
updateAccountValue: AccruedDividend 0.00 USD DU58265
updateAccountValue: AccruedDividend-S 0.00 USD DU58265
updateAccountValue: AvailableFunds 984986.06 USD DU58265
updateAccountValue: AvailableFunds-S 984986.06 USD DU58265
updateAccountValue: Billable 0.00 USD DU58265
updateAccountValue: Billable-S 0.00 USD DU58265
updateAccountValue: BuyingPower 3939894.24 USD DU58265
updateAccountValue: CashBalance 978048.56 BASE DU58265
updateAccountValue: CashBalance 978048.56 USD DU58265
updateAccountValue: Currency BASE BASE DU58265
updateAccountValue: Currency USD USD DU58265
updateAccountValue: Cushion 0.997617 DU58265
updateAccountValue: DayTradesRemaining -1 DU58265
updateAccountValue: DayTradesRemainingT+1 -1 DU58265
updateAccountValue: DayTradesRemainingT+2 -1 DU58265
updateAccountValue: DayTradesRemainingT+3 -1 DU58265
updateAccountValue: DayTradesRemainingT+4 -1 DU58265
updateAccountValue: EquityWithLoanValue 987298.56 USD DU58265
updateAccountValue: EquityWithLoanValue-S 987298.56 USD DU58265
updateAccountValue: ExcessLiquidity 984986.06 USD DU58265
updateAccountValue: ExcessLiquidity-S 984986.06 USD DU58265
updateAccountValue: ExchangeRate 1.00 BASE DU58265
updateAccountValue: ExchangeRate 1.00 USD DU58265
updateAccountValue: FullAvailableFunds 984986.06 USD DU58265
updateAccountValue: FullAvailableFunds-S 984986.06 USD DU58265
updateAccountValue: FullExcessLiquidity 984986.06 USD DU58265
updateAccountValue: FullExcessLiquidity-S 984986.06 USD DU58265
updateAccountValue: FullInitMarginReq 2312.50 USD DU58265
updateAccountValue: FullInitMarginReq-S 2312.50 USD DU58265
updateAccountValue: FullMaintMarginReq 2312.50 USD DU58265
updateAccountValue: FullMaintMarginReq-S 2312.50 USD DU58265
updateAccountValue: FutureOptionValue 0.00 BASE DU58265
updateAccountValue: FutureOptionValue 0.00 USD DU58265
updateAccountValue: FuturesPNL 0.00 BASE DU58265
updateAccountValue: FuturesPNL 0.00 USD DU58265
updateAccountValue: GrossPositionValue 9290.00 USD DU58265
updateAccountValue: GrossPositionValue-S 9290.00 USD DU58265
updateAccountValue: InitMarginReq 2312.50 USD DU58265
updateAccountValue: InitMarginReq-S 2312.50 USD DU58265
updateAccountValue: Leverage-S 0.01 DU58265
updateAccountValue: LookAheadAvailableFunds 984986.06 USD DU58265
updateAccountValue: LookAheadAvailableFunds-S 984986.06 USD DU58265
updateAccountValue: LookAheadExcessLiquidity 984986.06 USD DU58265
updateAccountValue: LookAheadExcessLiquidity-S 984986.06 USD DU58265
updateAccountValue: LookAheadInitMarginReq 2312.50 USD DU58265
updateAccountValue: LookAheadInitMarginReq-S 2312.50 USD DU58265
updateAccountValue: LookAheadMaintMarginReq 2312.50 USD DU58265
updateAccountValue: LookAheadMaintMarginReq-S 2312.50 USD DU58265
updateAccountValue: LookAheadNextChange 0 DU58265
updateAccountValue: MaintMarginReq 2312.50 USD DU58265
updateAccountValue: MaintMarginReq-S 2312.50 USD DU58265
updateAccountValue: NetLiquidation 987338.56 USD DU58265
updateAccountValue: NetLiquidation-S 987338.56 USD DU58265
updateAccountValue: NetLiquidationByCurrency 987338.56 BASE DU58265
updateAccountValue: NetLiquidationByCurrency 987338.56 USD DU58265
updateAccountValue: OptionMarketValue 40.00 BASE DU58265
updateAccountValue: OptionMarketValue 40.00 USD DU58265
updateAccountValue: PNL true DU58265
updateAccountValue: PreviousDayEquityWithLoanValue 987286.06 USD DU58265
updateAccountValue: PreviousDayEquityWithLoanValue-S 987286.06 USD DU58265
updateAccountValue: RealizedPnL 0.00 BASE DU58265
updateAccountValue: RealizedPnL 0.00 USD DU58265
updateAccountValue: RegTEquity 987298.56 USD DU58265
updateAccountValue: RegTEquity-S 987298.56 USD DU58265
updateAccountValue: RegTMargin 4625.00 USD DU58265
updateAccountValue: RegTMargin-S 4625.00 USD DU58265
updateAccountValue: SMA 984635.56 USD DU58265
updateAccountValue: SMA-S 984635.56 USD DU58265
updateAccountValue: StockMarketValue 9250.00 BASE DU58265
updateAccountValue: StockMarketValue 9250.00 USD DU58265
updateAccountValue: TotalCashBalance 978048.56 BASE DU58265
updateAccountValue: TotalCashBalance 978048.56 USD DU58265
updateAccountValue: TotalCashValue 978048.56 USD DU58265
updateAccountValue: TotalCashValue-S 978048.56 USD DU58265
updateAccountValue: UnalteredInitMarginReq -1.00 USD DU58265
updateAccountValue: UnalteredMaintMarginReq -1.00 USD DU58265
updateAccountValue: UnrealizedPnL -8555.88 BASE DU58265
updateAccountValue: UnrealizedPnL -8555.88 USD DU58265
updateAccountValue: WhatIfPMEnabled true DU58265
updatePortfolio: ---
contract_msg:
conid = 7516
symbol = GE
secType = STK
expiry =
strike = 0.0
right = 0
multiplier =
exchange =
primaryExch = ARCA
currency = USD
localSymbol = GE
position 200, mkt price 8.5550003, mkt value 1711.0, avg cost 16.745, unrealized p/l -1638.0, realized p/l 0.0 DU58265

updateAccountTime: 11:58
updatePortfolio: ---
contract_msg:
conid = 54528396
symbol = RUT
secType = OPT
expiry = 20090319
strike = 490.0
right = C
multiplier = 100
exchange =
primaryExch = AMEX
currency = USD
localSymbol = RUWCA
position 1, mkt price 0.4, mkt value 40.0, avg cost 5180.88, unrealized p/l -5140.88, realized p/l 0.0 DU58265

updateAccountTime: 11:58
updatePortfolio: ---
contract_msg:
conid = 756733
symbol = SPY
secType = STK
expiry =
strike = 0.0
right = 0
multiplier =
exchange =
primaryExch = ARCA
currency = USD
localSymbol = SPY
position 100, mkt price 75.3899994, mkt value 7539.0, avg cost 93.16, unrealized p/l -1777.0, realized p/l 0.0 DU58265

updateAccountTime: 11:58
updateAccountTime: 11:58
disconnected





03/09/09 Update

Upgrading to API v. 9.60
requires addition of these new callback methods.

 
# ---------------------------------------------------
# new callback methods added in API 9.60
# ---------------------------------------------------
def openOrderEnd() # invoked when all orders are sent to a client as a response to reqOpenOrders()
end

def accountDownloadEnd(account_name) #invoked when a complete snapshot of an account state is sent to a client as a response to reqAccountUpdates()
end

def execDetailsEnd( req_id) # invoked when all executions are sent to a client as a response to reqExecutions()
end

def deltaNeutralValidation(req_id, under_comp) # for Delta-Neutral DN RFQ
end

No comments: