提取多个帐户的API响应

时间:2015-07-29 17:01:39

标签: api python-2.7 pandas interactive-brokers ibpy

我是IBPy的新手,非常有兴趣了解如何获取多个帐户的帐户参数。下面的代码只给出了命令行中的输出,但我无法弄清楚如何将这些信息存储到数据帧中。函数updateAccountValue()没有唯一的id,我可以将其用作数据帧的索引。

from ib.opt import Connection, message
import pandas as pd
import time

def error_handler(msg):
    """Handles the capturing of error messages"""
    print "Server Error: %s" % msg

def updateAccount_handler(msg):
    if msg.key in ['AccountType','NetLiquidation']:
        print msg.key, msg.value

if __name__ == "__main__":
    conn = Connection.create(port=7497, clientId = 93)
    conn.connect()

    conn.register(error_handler, 'Error')
    conn.register(updateAccount_handler,message.updateAccountValue)

    # we can do a loop, i am just giving a simple example for 2 accounts
    conn.reqAccountUpdates(1,"Uxxxx008")
    time.sleep(0.5)

    conn.reqAccountUpdates(1,"Uxxxx765")
    time.sleep(0.5)

    conn.disconnect()

输出如下:

Server Version: 76
TWS Time at connection:20150729 12:46:56 EST
Server Error: <error id=-1, errorCode=2104, errorMsg=Market data farm connection is OK:usfuture>
Server Error: <error id=-1, errorCode=2104, errorMsg=Market data farm connection is OK:usfuture.us>
Server Error: <error id=-1, errorCode=2104, errorMsg=Market data farm connection is OK:usfarm>
Server Error: <error id=-1, errorCode=2106, errorMsg=HMDS data farm connection is OK:ushmds>
AccountType INDIVIDUAL
NetLiquidation 2625.24
AccountType IRA-ROTH NEW
NetLiquidation 11313.83

最终目标是将这些信息存储为具有唯一ID帐号的pandas数据框格式。

1 个答案:

答案 0 :(得分:1)

好的,IBpy适用于发送器/接收器架构。我想建议您使用全局变量来存储帐户信息。

from ib.opt import Connection, message
import pandas as pd
import time
class account_update :
   acc_info = [] # list to store all your account info
   # you can have list,tuple,panda dataframe or any data strucure I am using normal list to demonstrate
   def error_handler(self,msg):
       """Handles the capturing of error messages"""
       print "Server Error: %s" % msg

   def updateAccount_handler(self,msg):
       if msg.key in ['AccountType','NetLiquidation']:
           self.acc_info.append(msg.key, msg.value)

   def main(self):
       conn = Connection.create(port=7497, clientId = 93)
       conn.connect()

       conn.register(error_handler, 'Error')
       conn.register(updateAccount_handler,message.updateAccountValue)

       conn.reqAccountUpdates(1,"Uxxxx008")
       time.sleep(0.5)

       conn.reqAccountUpdates(1,"Uxxxx765")
       time.sleep(0.5)

       conn.disconnect()

if __name__ == "__main__" :
     account_update().main()

因此逻辑很简单,创建一个全局变量并使响应处理程序方法在收到响应时更新全局变量。希望它有效:)