0

I have a class "contractDetails" that I am printing. I want to get a specific result from it (the 5th element).

Here is the code:

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import *
from ibapi.contract import *

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

    def contractDetails(self, reqId, contractDetails):
        print(contractDetails)

    def start(self):
        contract = Contract()
        contract.symbol = 'AAPL'
        contract.secType = 'OPT'
        contract.currency = 'USD'
        contract.exchange = 'SMART'
        contract.lastTradeDateOrContractMonth = '202011'

        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,101)

    app.run()

if __name__ == "__main__":
    main()

I get something like this:

423554420,AAPL,OPT,20201120,450.0,P,100,SMART...

I want to print only the 5th element there, the "450.0". (the strike price)

I've tried

print(contractDetails[5])

But I get an error "TypeError: 'ContractDetails' object is not subscriptable"

I can print other ones alone using "contractDetails.underSymbol" for example. But looking through the list (https://interactivebrokers.github.io/tws-api/classIBApi_1_1ContractDetails.html) and trying them all none of them give me the one I want.

From what I understand it's a value that is passed to the contract using "contract.strike", and when no value is provided it prints out the list of all available strikes.

EDIT: from the comments...."contractDetails.contract.strike" works.

Mitch
  • 553
  • 1
  • 9
  • 24
  • What error do you get, exactly? What is the type of `contractDetails`? Is there any documentation for `ibapi`? – Samwise May 23 '20 at 05:32
  • Updated with the error and link. Yes there is, https://interactivebrokers.github.io/tws-api/contract_details.html. – Mitch May 23 '20 at 05:40
  • 1
    The error message tells you that you can't use subscript syntax (`[n]`) on this object. Maybe you could use `contractDetails.contract.strike`? – Samwise May 23 '20 at 05:47
  • 1
    `print(contractDetails)` may work because that object has a `__str__()` or `__repr__()` defined. Though it appears the same way a list, the object does not have subscripting defined with `__getitem__()`. Like @Samwise, I also suggest accessing the strike price explicitly. – luthervespers May 23 '20 at 05:52
  • @Samwise contractDetails.contract.strike worked! I'll update the answer, thanks. – Mitch May 23 '20 at 06:40

1 Answers1

0

If the contractDetails is not a list ,You can try converting the contractdetails into a list using list() or try following approch,

j=0
for i in range contractDetails:
   if j==4:
      print(i)
   j+=1
Prathamesh
  • 1,064
  • 1
  • 6
  • 16