As the title indicates, I am trying to get the price of a given security from TWS API and use it as a variable in my program elsewhere. The below code (straight from one of Interactive Broker's tutorials) will run and print the price out on the screen but I haven't been able to alter it in a way that works in getting to create a variable/object that contains the price. The code also only works about once in every ten tries, if there is something I'm doing wrong there, please let me know.
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.ticktype import TickTypeEnum
class TestApp(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
def error(self, reqId, errorCode, errorString):
print('Error: ', reqId, ' ', errorCode, ' ', errorString)
def tickPrice(self, reqId, tickType, price, attrib):
print('Tick Price. Ticker Id:', reqId, 'tickType:', TickTypeEnum.to_str(tickType),
'Price:', price, end=' ')
def main():
app = TestApp()
app.connect('127.0.0.1', 7496, 0)
contract = Contract()
contract.symbol = 'AAPL'
contract.secType = 'STK'
contract.currency = 'USD'
contract.exchange = 'SMART'
app.reqMarketDataType(1)
app.reqMktData(1, contract, '', False, False, [])
app.run()
if __name__ == '__main__':
main()