'Export contractDetails to df or csv from TWS API in Python?

This question has actually already been asked and answered on another forum, howwwever, the answer was given through a web link and it appears as if that link has indeed expired. Thus I am forced to ask the question again to you lovely intelligent people.

Does anyone know how to export data from "contractDetails" to a df or a CSV file? This is the code so far:

class TestApp(EWrapper, EClient):
    def __init__(self):
        EWrapper.__init__(self)
        EClient.__init__(self, self)​

    def contractDetails(self, reqId, contractDetails):
        self.data = [contractDetails]
        df = pd.DataFrame(self.data)
        df.to_csv('options_test.csv')
        print(df)​

    def contractDetailsEnd(self, reqId):
        print("\ncontractDetails End\n")​

    def start(self):
        contract = Contract()
        contract.symbol = 'AAPL'
        contract.secType = 'OPT'
        contract.exchange = 'SMART'
        contract.currency = 'USD'
        #contract.primaryExchange = 'NASDAQ'
        contract.lastTradeDateOrContractMonth = '202301'
        #contract.strike = 175
        #contract.right = "C"
        #contract.multiplier = "100"
        global underlying
        underlying = contract.symbol​

        self.reqMktData(1, contract, '106', False, False, [])​

        self.reqContractDetails(1, contract)​

    def stop(self):
        self.done = True
        self.disconnect()​

    def main():
        app = TestApp()
        app.nextOrderId = 0
        app.connect('127.0.0.1', 7497, 123)
        app.data = []​

        Timer(4, app.stop).start()
        app.run()​

if __name__ == "__main__":
    main()​

This is the link to the original question: https://www.elitetrader.com/et/thre...details-to-csv-from-tws-api-in-python.344314/

And this is the link to the original answer: https://repl.it/repls/DamagedStandardDeprecatedsoftware

If anyone can figure this out, be rest assured, dinner is on me (Y)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source