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

Discussion in 'Interactive Brokers' started by ReachMani, Jan 26, 2022.

  1. ReachMani

    ReachMani

    This question has actually already been asked and answered on here, 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 ='202010'
    #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)

    Thank you for your time.
     
  2. 2rosy

    2rosy

  3. ReachMani

    ReachMani

  4. ReachMani

    ReachMani

    To prevent this issue from reoccurring in the future for someone else, here is the syntax that I am using based off of the answer @2rosy provided me with:

    from ib_insync import *
    util.startLoop()

    import logging
    # util.logToConsole(logging.DEBUG)

    ib = IB()
    ib.connect('127.0.0.1', 7497, clientId=1)


    spy = Option('SPY', '202301', '', 'C', 'SMART')

    cds = ib.reqContractDetails(spy)

    len(cds)

    contracts = [cd.contract for cd in cds]

    contracts[0]

    util.df(contracts)

    print(util.df(contracts))​


    Thank you again @2rosy!