简体   繁体   中英

ibpy how to get commission using interactive broker's API?

I have following code that use python API of IB, it should display both price and commission:

from ib.ext.ExecutionFilter import ExecutionFilter 
from ib.ext.CommissionReport import CommissionReport
from ib.opt import ibConnection, message 

from time import sleep 

#-- message handlers ------------------------------------------------- 

# print all messages from TWS 
def watcher(msg): 
    pass 

def ExecutionDetailsHandler(msg): 
    global execDetails 
    execDetails = msg.execution 
    #print execDetails.m_price 
    #print execDetails.m_side 

def CommissionDetailsHandler(msg): 
    global commission 
    commission = msg.commissionReport

# global variable that stores the last Execution seen by 
ExecutionDetailsHandler 
CommissionDetailsHandler
execDetails = None 
commission = None

#-- factories 
#----------------------------------------------------------- 

def makeExecFilter(): 
    filter=ExecutionFilter() 
    return filter 

#-- utilities -------------------------------------------------------- 

def getExecutionPrice(): 
    filter=makeExecFilter() 
    con.reqExecutions(744,filter) 

    # wait for TWS message to come back to message handler 
    while execDetails is None: 
        print 'waiting' 
        sleep(1) 
    return execDetails.m_price 

def getCommission(): 
    filter=CommissionReport() 
    con.commissionReport(filter) 

    # wait for TWS message to come back to message handler 
    while commission is None: 
        print 'waiting' 
        sleep(1) 
    return commission.m_commission

con = ibConnection() 
con.registerAll(watcher) 
con.register(ExecutionDetailsHandler, 'ExecDetails') 
con.register(CommissionDetailsHandler, 'commissionDetails') 
con.connect() 

price=getExecutionPrice() 
c = getCommission()
con.disconnect()
print 'The price of one execution is:', price 
print 'The commission fee is:', c 

however this is only working for execution price, as it displays the price information after print out. But it does not show the commission information (in my terminal it keeps waiting forever), is there anything wrong in my code?

thx for brian's answer, this does the trick:

commission = None

def commReport(msg):
    global commission
    #print('ID',msg.commissionReport.m_execId,'COM',msg.commissionReport.m_commission)
    commission = msg.commissionReport.m_commission

conn = Connection.create(port=7496, clientId=222)
conn.register(commReport, message.commissionReport)
conn.connect()

and now I am happy to use commission anywhere i want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM