import sys import signal import datetime from ibapi.client import EClient, Order from ibapi.wrapper import EWrapper from ibapi.utils import iswrapper #tgtAccts = [ 'DU7991273' ] # "real" paper #tgtAccts = [ 'DU7991274' ] # test paper tgtAccts = [ 'U13232746' ] # LIVE #tgtTags = [ 'NetLiquidationByCurrency', 'UnrealizedPnL' ] class IBapi(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) self.pos = {} self.ctracts = {} self.fooID = None @iswrapper def nextValidId(self, orderId:int): print('set next order id to %s' % orderId) self.fooID = orderId self.reqPositions() @iswrapper def position(self, account, contract, pos, avgCost): if account in tgtAccts:# and pos > 0: #print('position: account %s contract %s pos %s avgCost %s' % (account, contract, pos, avgCost)) if contract.secType == 'STK': #print('contract symbol %s sectype %s pos %s' % (contract.symbol, contract.secType, pos)) self.pos[contract.symbol] = pos self.ctracts[contract.symbol] = contract @iswrapper def positionEnd(self): print('close out these guys:') print(str(self.pos)) for sym, amt in self.pos.items(): order = Order() order.action = 'SELL' if amt > 0 else 'BUY' order.orderType = 'MOC' order.totalQuantity = amt order.account = tgtAccts[0] self.ctracts[sym].exchange = 'SMART' self.placeOrder(self.fooID, self.ctracts[sym], order) self.fooID += 1 app = IBapi() def signal_handler(sig, frame): print('You pressed Ctrl+C!') app.disconnect() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) app.connect('tws2', 7496, 223) app.run()