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

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()
 
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.

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.
 
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.

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
 
Back
Top