I am using the IB API to retrieve historical stock data, and I would like my code to run multiple times with different variables (different stocks and timeframes).
Currently I am using the following code:
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
def print_to_file(*args):
with open('text6.txt', 'a') as fh:
fh.write(' '.join(map(str,args)))
fh.write('\n')
print = print_to_file
class TestApp(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
Layout = "{!s:1} {!s:2} {!s:3} {!s:4} {!s:5} {!s:6} {!s:7} {!s:8} {!s:8} '\n'"
print(Layout.format("Ticker;", "Date;", "None;", "Time;", "Open;", "High;", "Low;", "Close;", "Volume"))
def historicalData(self, reqId, bar):
print("AAPL", ";", bar.date.replace(' ', '; '), ";", bar.open, ";", bar.high, ";", bar.low, ";", bar.close, ";", bar.volume)
def main():
app = TestApp()
app.connect("127.0.0.1", 7497, 0)
contract = Contract ()
contract.symbol = "AAPL"
contract.secType = "STK"
contract.exchange = "SMART"
contract.currency = "USD"
contract.primaryExchange = "NASDAQ"
app.reqHistoricalData(0, contract, "20180201 10:00:00", "1 M", "1 min", "TRADES", 0, 1, False, [])
app.run()
if __name__ == "__main__":
main()
I have tried the following for multiple stocks:
contract.symbol = ["AAPL", "GOOG"]
But this gives me the error message:
No security definition has been found for the request
And using the following code for time & date:
app.reqHistoricalData(0, contract, ["20180201 10:00:00", "20180301 10:00:00"], "1 M", "1 min", "TRADES", 0, 1, False, [])
Gives me the error message:
Error validating request:-'bP' : cause - Historical data query end date/time string [['20180201 10:00:00', '20180301 10:00:00']] is invalid. Format is 'YYYYMMDD{SPACE}hh:mm:ss[{SPACE}TMZ]'.
Basically I would like this .py file to run multiple requests in a single run, using multiple variables so that I can receive data for multiple stocks in a single run.
Could anybody here help me to achieve this?
Thanks!