Im using an API from Interactive Brokers to get historical data and I am using their code to download the data.
The code uses the print function to output the data to the terminal, but I would like to redirect it to a file (lets call that file StockData.txt)
The code I am using is:
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
class TestApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
    def error(self, reqId, errorCode, errorString):
        print("error: ", reqId, " ", errorCode, " ", errorString)
    def historicalData(self, reqId, bar):
        print("HistoricalData. ", reqId, " Date:", bar.date, "Open:", bar.open, "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", 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, "", "1 D", "1 min", "TRADES", 0, 1, False, [])
    app.run()
if __name__ == "__main__":
    main()
Like I said, I would like the API to write to StockData.txt, but I am unsure how to do this since it's not my code and I am not that savvy in Python.
Could anyone help me out here? Thanks!
 
    