我正在尝试使用ibpy库从交互式代理获取汇率,我在google上找到了一些代码,我做了一些修改。在from ib.ext.Contract import Contract
from ib.opt import ibConnection, message
from time import sleep
# print all messages from TWS
def watcher(msg):
print msg
# show Bid and Ask quotes
def my_BidAsk(msg):
if msg.field == 1:
print ('bid: %s' % ( msg.price))
bid=msg.price
elif msg.field == 2:
print ('ask: %s' % (msg.price))
ask=msg.price
elif msg.field==9:
print ('last close: %s' % msg.price)
last=msg.price
def makeStkContract(contractTuple):
newContract = Contract()
newContract.m_symbol = contractTuple[0]
newContract.m_secType = contractTuple[1]
newContract.m_exchange = contractTuple[2]
newContract.m_primaryExch=contractTuple[3]
newContract.m_currency = contractTuple[4]
print ('Contract Values:%s,%s,%s,%s,%s:' % contractTuple)
return newContract
if __name__ == '__main__':
global bid,ask,last
bid=None
ask=None
last=None
# con = ibConnection(port='4001',clientId=100)
con = Connection.create(port=7497, clientId=1006)
con.registerAll(watcher)
showBidAskOnly = True # set False to see the raw messages
if showBidAskOnly:
con.unregister(watcher, message.tickSize, message.tickPrice,
message.tickString, message.tickOptionComputation)
con.register(my_BidAsk, message.tickPrice)
con.connect()
sleep(1)
tickId = 1
# Note: Option quotes will give an error if they aren't shown in TWS
#contractTuple = ('GOOGL', 'STK', 'SMART', 'ISLAND','USD')
#contractTuple = ('QQQQ', 'OPT', 'SMART', 'USD', '20170921', 47.0, 'CALL')
#contractTuple = ('ES', 'FUT', 'GLOBEX', 'USD', '200709', 0.0, '')
#contractTuple = ('ES', 'FOP', 'GLOBEX', 'USD', '20070920', 1460.0, 'CALL')
contractTuple = ('CAD', 'CASH', 'IDEALPRO','IDEALPRO','jpy')
stkContract = makeStkContract(contractTuple)
print ('* * * * REQUESTING MARKET DATA * * * *')
con.reqMktData(tickId, stkContract, '', False)
print ('global variables:',bid, ask,last)
sleep(1)
print ('* * * * CANCELING MARKET DATA * * * *')
con.cancelMktData(tickId)
sleep(1)
con.disconnect()
#sleep(1)
结果如下
^{pr2}$
我现在遇到的困难是,首先我想消除所有不相关的msg,其次,我似乎不能让全局变量(bid,ask,last)起作用。在
有什么建议吗?
提前谢谢