erdewit / ib_insync

Python sync/async framework for Interactive Brokers API
BSD 2-Clause "Simplified" License
2.75k stars 723 forks source link

Parse ib.positions #25

Closed chadhumphrey closed 6 years ago

chadhumphrey commented 6 years ago

So I get this list back from interactive brokers.

`b = IB() ib.connect('127.0.0.1', 7497, clientId=2)

data = ib.positions()
print((data))
print(type(data))`

The data comes back as , but here is the response.

[Position(account='DUC00074', contract=Contract(conId=43645865, symbol='IBKR', secType='STK', exchange='NASDAQ', currency='USD', localSymbol='IBKR', tradingClass='NMS'), position=2800.0, avgCost=39.4058383), Position(account='DUC00074', contract=Contract(conId=72063691, symbol='BRK B', secType='STK',exchange='NYSE', currency='USD', localSymbol='BRK B', tradingClass='BRK B'), position=250.0, avgCost=163.4365424)]

I have got this far:

`for x in data: print(type(x)) print(objects)

<class 'ib_insync.objects.Position'>

But I have no idea as to how I would parse and then dump into a DB, anything after Position(... So to be really clear, I don't know how I would parse, like I would say in php / json. Also what type of class is<class 'ib_insync.objects.Position'>`

chadhumphrey commented 6 years ago

Okay, Im new to python, not new to programing. So the response from Interactive Brokers threw me off. I'm so used to JSON response. Regardless, what it comes down to is this is a list of objects, (the example above). That might be simple, but missed it. Once I figured it out it became a little easier.

Here is the final code, hopefully this will help someone else down the line.



#the line below just bascially dumps the object
print("obj={}  ".format(obj))

#looking for account number
#"contract" is an object inside an object, so I had to extract that. 
if(getattr(obj, 'account') == '123456'):
    print("x={}  ".format(getattr(obj, 'account')))
    account = (getattr(obj, 'account'))
    contract = getattr(obj, 'contract')
    contractId = getattr(contract, 'conId')
    symbol = getattr(contract, 'symbol')
    secType = getattr(contract, 'secType')
    exdate = getattr(contract, 'lastTradeDateOrContractMonth')
    strike = getattr(contract, 'strike')
    opt_type = getattr(contract, 'right')
    localSymbol = getattr(contract, 'localSymbol')
    position = getattr(obj, 'position')
    avgCost = getattr(obj, 'avgCost')

    sql = "insert into IB_opt (account, contractId, symbol, secType, exdate, opt_type, localSymbol, position, avgCost,strike) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)";
    args = (account, contractId, symbol, secType, exdate, opt_type, localSymbol, position, avgCost,strike)
    cursor.execute(sql, args)```
erdewit commented 6 years ago

Instead of getattr(obj, 'account') just use obj.account, or obj.contract.symbol, etc. I suppose the dot operator is what you meant by parsing.