How to export contractDetails to csv from TWS API in Python>?

Discussion in 'Interactive Brokers' started by chami, May 4, 2020.

  1. chami

    chami

    I'm trying to export data from "contractDetails" to csv. So far I've only managed to make it rewrite itself and print out the last line from contractDetails.

    Here is the relevant code:

    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()
     
    ReachMani likes this.
  2. Alexpung

    Alexpung

    Not a panda expert
    I think you need to set append mode when calling df.to_csv

    also to skip header for 2nd+ calls
     
  3. d08

    d08

    ReachMani likes this.
  4. chami

    chami

    I get an error "NameError: name 'self' is not defined" from the line "
    self.outCsv = csv.writer(open(r"mycsv.csv",'wb'))" in the main() function.
     
  5. d08

    d08

    Because it's outside of the class, the formatting of the code you pasted was poor, wasn't evident.

    Just use app.outCsv instead of self.outCsv.
     
    Baron likes this.
  6. chami

    chami

    Thanks that worked.
    Just had to change
    app.outCsv = csv.writer(open(r"mycsv.csv",'wb'))
    to
    app.outCsv = csv.writer(open(r"mycsv.csv",'w'))
    or else it throws a "binary" typeerror
     
    ReachMani and d08 like this.
  7. ReachMani

    ReachMani

    @d08
    @d08 the original link seems to have expired (or just isn't working for me) and I can't access the syntax. If it's not too much trouble could you please repost it or send it to me?