2016-12-06 116 views
1

我寫了一個腳本,從我的股票交易,它看起來像這樣獲得的賬面價值(工作):如何將異步設計模式轉換爲同步模式?

from ib.opt import ibConnection, message 
def account_summary_handler(msg): 
    print(msg.tag, msg.value, msg.currency) 
    connection.cancelAccountSummary(1) 
    connection.disconnect() 

connection = ibConnection(port=7497, clientId=100) 
connection.register(account_summary_handler, 'AccountSummary') 
connection.connect() 
connection.reqAccountSummary(1, 'All', 'NetLiquidation') 

這是一個實時的API,所以一旦連接是打開的,更新流,並my_account_handler每次更新都會被調用。

我想從另一個同步腳本中的賬戶餘額,像,被稱爲是這樣的:

myaccount.account_summary() 

我寫的東西,看起來像這樣(未經):

class IBAccount(object): 
    def __init__(self): 
     self.clientId=100 
     self.port=7497 

    def connect(self): 
     self.connection = ibConnection(port=self.port, clientId=self.clientId) 

    def account_summary(self): 
     self.connection.register(self.account_summary_handler, 'AccountSummary') 
     connection.connect() 
     connection.reqAccountSummary(1, 'All', 'NetLiquidation') 

    def account_summary_handler(self, msg): 
     self.connection.cancelAccountSummary(1) 
     self.connection.disconnect() 
     return msg.value 

我相信我需要account_summary()來阻止並返回實際的賬戶值,而不是通過不同的函數返回。

我的問題是: 如何獲取account_summary()以返回帳戶值?

此外,如果我對此代碼使用了不適當的設計模式,並且不應該使用類,請告知。

回答

0

解決的辦法是讓它說:

從ib.opt進口ibConnection,消息

class IBstate(object): 

    def __init__(self): 
     self.clientId=100 
     self.port=7496 
     self.netLiquidation = None 

     self.connection = ibConnection(port=self.port, clientId=self.clientId) 
     self.connection.connect() 
     self.connection.register(self.account_summary_handler, 'AccountSummary') 
     self.connection.reqAccountSummary(1, 'All', 'NetLiquidation')  

    def account_summary_handler(self, msg): 
     self.netLiquidation = msg 

這在後臺運行,併爲他們改變對端更新對象的變量。