Reputation: 51
I found a great block of code to extract the current positions from an Interactive Brokers account through their API. Here is the link to this code: How do I get my accounts' positions at Interactive Brokers using Python API?
It works super well and I am very happy with it but I have several positions in different currencies. A work around I implemented now is to map a dictionary like this:
ticker_to_currency = {
'VOO': 'USD',
'VXF' : 'EUR'
}
positions['Currency'] = positions['Symbol'].map(ticker_to_currency)
However, I am wondering if there is a more robust solution in which the currency can just be extracted straight from the API.
Upvotes: 1
Views: 77
Reputation: 10989
The currency is in the contract object.
from ibapi import wrapper
from ibapi.client import EClient
from ibapi.contract import *
from ibapi.common import *
import pandas as pd
class Get_All_Positions(wrapper.EWrapper, EClient):
def __init__(self):
wrapper.EWrapper.__init__(self)
EClient.__init__(self, wrapper=self)
self.positions = pd.DataFrame([], columns = ['secType','currency', 'quantity', 'average_cost'] )
def nextValidId(self, orderId:int):
self.nextValidOrderId = orderId
self.reqPositions()
def position(self, account: str, contract: Contract, position: float, avgCost: float):
self.positions.loc[contract.symbol]=contract.secType,contract.currency,position,avgCost
def positionEnd(self):
print('end get positions')
self.disconnect()
print(self.positions)
def error(self, reqId:TickerId, errorCode:int, errorString:str, ):
print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)
tws_port = 7497
IB_API=Get_All_Positions()
IB_API.connect("127.0.0.1", tws_port, clientId=123)
IB_API.run()
Upvotes: 1