我已经看过这里的所有内容,我的帮助,但它似乎没有用,我在编程方面相对较新,任何回复都将受到高度赞赏。 我需要能够将Apple的股票价格下载到变量中并打印出来。我正在使用Interactive Brokers的演示版' TWS。
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 ('%s:%s: bid: %s' % (contractTuple[0],
contractTuple[6], msg.price))
elif msg.field == 2:
print ('%s:%s: ask: %s' % (contractTuple[0], contractTuple[6], msg.price))
def makeStkContract(contractTuple):
newContract = Contract()
newContract.m_symbol = contractTuple[0]
newContract.m_secType = contractTuple[1]
newContract.m_exchange = contractTuple[2]
newContract.m_currency = contractTuple[3]
newContract.m_expiry = contractTuple[4]
newContract.m_strike = contractTuple[5]
newContract.m_right = contractTuple[6]
print ('Contract Values:%s,%s,%s,%s,%s,%s,%s:' % contractTuple)
return newContract
if __name__ == '__main__':
con = ibConnection()
con.registerAll(watcher)
showBidAskOnly = False # 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 = 59
# Note: Option quotes will give an error if they aren't shown in TWS
contractTuple = ('AAPL', 'STK', 'SMART', 'USD', '', 0.0, '')
#contractTuple = ('QQQQ', 'OPT', 'SMART', 'USD', '20070921', 47.0, 'CALL')
#contractTuple = ('ES', 'FUT', 'GLOBEX', 'USD', '200709', 0.0, '')
#contractTuple = ('ES', 'FOP', 'GLOBEX', 'USD', '20070920', 1460.0, 'CALL')
#contractTuple = ('EUR', 'CASH', 'IDEALPRO', 'USD', '', 0.0, '')
stkContract = makeStkContract(contractTuple)
print ('* * * * REQUESTING MARKET DATA * * * *')
con.reqMktData(tickId, stkContract, 'AAPL', False)
sleep(15)
print ('* * * * CANCELING MARKET DATA * * * *')
con.cancelMktData(tickId)
sleep(1)
con.disconnect()
sleep(1)
这是我从IbPy获得的代码。
答案 0 :(得分:1)
我假设你在粘贴代码时搞砸了格式化。否则它永远不会起作用。
如果您收到错误回调,可能会看到类似“无效通用标记”的内容。您将'AAPL'放在您指定所需类型的刻度的位置。只需将其留空以获得正常的刻度。
con.reqMktData(tickId, stkContract, '', False)
我不确定演示使用的端口和ID,但如果不是7496,0,则可以在此指定(默认值)。
例如。 con = ibConnection(port = 7497, clientId = 123)