def my_callback_handler(self, msg): """ Simple call back handler """ if msg.typeName == "contractDetails": opt_contract = msg.values()[1] OPTIONS.loc[str(opt_contract.m_summary.m_conId).replace(" ", ""),\ 'm_conId'] = opt_contract.m_summary.m_conId OPTIONS.loc[str(opt_contract.m_summary.m_conId).replace(" ", ""),\ 'm_symbol'] = opt_contract.m_summary.m_symbol OPTIONS.loc[str(opt_contract.m_summary.m_conId).replace(" ", ""),\ 'm_secType'] = opt_contract.m_summary.m_secType OPTIONS.loc[str(opt_contract.m_summary.m_conId).replace(" ", ""),\ 'm_expiry'] = opt_contract.m_summary.m_expiry OPTIONS.loc[str(opt_contract.m_summary.m_conId).replace(" ", ""),\ 'm_strike'] = opt_contract.m_summary.m_strike OPTIONS.loc[str(opt_contract.m_summary.m_conId).replace(" ", ""),\ 'm_right'] = opt_contract.m_summary.m_right OPTIONS.loc[str(opt_contract.m_summary.m_conId).replace(" ", ""),\ 'm_multiplier'] = opt_contract.m_summary.m_multiplier OPTIONS.loc[str(opt_contract.m_summary.m_conId).replace(" ", ""),\ 'm_exchange'] = opt_contract.m_summary.m_exchange OPTIONS.loc[str(opt_contract.m_summary.m_conId).replace(" ", ""),\ 'm_currency'] = opt_contract.m_summary.m_currency OPTIONS.loc[str(opt_contract.m_summary.m_conId).replace(" ", ""),\ 'm_localSymbol'] = opt_contract.m_summary.m_localSymbol elif msg.typeName == "tickOptionComputation": sys.stdout.write('=> option computation update for tickerId %s\n' \ % msg.tickerId) if tt.getField(msg.field) == "askOptComp" or \ tt.getField(msg.field) == "bidOptComp" or \ tt.getField(msg.field) == "modelOptComp": field = "bid" if tt.getField(msg.field) == "bidOptComp" else \ "ask" if tt.getField(msg.field) == "askOptComp" else "last" OPTIONS.loc[str(msg.tickerId), '%s_impliedVol' % field] = \ msg.impliedVol OPTIONS.loc[str(msg.tickerId), '%s_delta' % field] = msg.delta OPTIONS.loc[str(msg.tickerId), '%s_gamma' % field] = msg.gamma OPTIONS.loc[str(msg.tickerId), '%s_theta' % field] = msg.theta OPTIONS.loc[str(msg.tickerId), '%s_vega' % field] = msg.vega OPTIONS.loc[str(msg.tickerId), '%s_optPrice' % field] = \ msg.optPrice OPTIONS.loc[str(msg.tickerId), '%s_undPrice' % field] = \ msg.undPrice elif msg.typeName == "historicalData": if ('finished' in str(msg.date)) == False: addentry = True entrydate = int(msg.date) * 1000 if self.latestdate and entrydate < self.latestdate: addentry = False if addentry: dataStr = [entrydate, msg.open, msg.high, msg.low, \ msg.close] self.NEWDATALIST = self.NEWDATALIST + [dataStr] volStr = [entrydate, msg.volume] self.NEWVOLUMELIST = self.NEWVOLUMELIST + [volStr]
def fieldTypes(): """ Creates mapping of ticker data fields to field names. @return field to field name mapping """ items = [(k, getattr(TickType, k)) for k in dir(TickType)] items = [(k, v) for k, v in items if isinstance(v, int)] unknown = TickType.getField(-1) items = [(v, TickType.getField(v)) for k, v in items] return dict([(k, v) for k, v in items if v != unknown])
def my_callback_handler(msg): #for reference on this /home/deep/development/IbPy/ib/ext/TickType #another class method tt.getField(msg.field) if msg.field in [ tt.BID, tt.ASK, tt.LAST, tt.HIGH, tt.LOW, tt.OPEN, tt.CLOSE ]: print(tt.getField(msg.field), msg.price) elif msg.field in [ tt.BID_SIZE, tt.ASK_SIZE, tt.LAST_SIZE, tt.VOLUME, tt.AVG_VOLUME ]: print(tt.getField(msg.field), msg.size) elif msg.field in [tt, LAST_TIMESTAMP]: print(tt.getField(msg.field), msg.time)
def setupTree(self): """ Configure the model and initial items for this instance. @return None """ tree = self.controlsTree self.controlsTreeModel = model = QStandardItemModel(self) tree.setModel(model) model.setHorizontalHeaderLabels(['Line', 'Value']) tree.sortByColumn(0, Qt.AscendingOrder) try: ticker = self.collection[self.key] except ( KeyError, TypeError, ): pass else: for field, series in ticker.series.items(): self.addSeries(TickType.getField(field), series) self.connect(model, Signals.standardItemChanged, self.on_controlsTree_itemChanged) for col in range(model.columnCount()): tree.resizeColumnToContents(col) tree.addActions([ self.actionChangeCurveStyle, self.actionChangeDataMarker, self.actionChangeCurveAxisX, self.actionChangeCurveAxisY, ]) tree.expandAll()
def setupTree(self): """ Configure the model and initial items for this instance. @return None """ tree = self.controlsTree self.controlsTreeModel = model = QStandardItemModel(self) tree.setModel(model) model.setHorizontalHeaderLabels(['Line', 'Value']) tree.sortByColumn(0, Qt.AscendingOrder) try: ticker = self.collection[self.key] except (KeyError, TypeError, ): pass else: for field, series in ticker.series.items(): self.addSeries(TickType.getField(field), series) self.connect(model, Signals.standardItemChanged, self.on_controlsTree_itemChanged) for col in range(model.columnCount()): tree.resizeColumnToContents(col) tree.addActions( [self.actionChangeCurveStyle, self.actionChangeDataMarker, self.actionChangeCurveAxisX, self.actionChangeCurveAxisY,]) tree.expandAll()
def tickEFP(cls, tickerId, tickType, basisPoints, formattedBasisPoints, impliedFuture, holdDays, futureExpiry, dividendImpact, dividendsToExpiry): """ generated source for method tickEFP """ return "id=" + str(tickerId) + " " + TickType.getField(tickType) \ + ": basisPoints = " + str(basisPoints) + "/" + formattedBasisPoints \ + " impliedFuture = " + str(impliedFuture) + " holdDays = " + str(holdDays) \ + " futureExpiry = " + futureExpiry + " dividendImpact = " + str(dividendImpact) \ + " dividends to expiry = " + str(dividendsToExpiry)
def fieldSpecs(maxValue=10): """ Yields one description dictionary for every TickType field. """ values = [getattr(TickType, k) for k in dir(TickType)] for value in [v for v in values if isinstance(v, int) and v < maxValue]: title = tickFieldTitle(TickType.getField(value)) yield dict(value=value, title=title)
def fieldSpecs(): """ Yields one description dictionary for every TickType field. """ values = [getattr(TickType, k) for k in dir(TickType)] for value in [v for v in values if isinstance(v, int)]: name = TickType.getField(value) title = tickFieldTitle(name) yield dict(sort=value, value=value, name=name, title=title)
def tickEFP(cls, tickerId, tickType, basisPoints, formattedBasisPoints, impliedFuture, holdDays, futureExpiry, dividendImpact, dividendsToExpiry): return "id=" + tickerId + " " + TickType.getField(tickType) + ": basisPoints = " + basisPoints + "/" + formattedBasisPoints + " impliedFuture = " + impliedFuture + " holdDays = " + holdDays + " futureExpiry = " + futureExpiry + " dividendImpact = " + dividendImpact + " dividends to expiry = " + dividendsToExpiry
def tickSizeHandler(self, msg): """Handle TickSize messages from IB. Store tick data in db @param msg ib.opt.message.TickSize Message sent by IB """ symb = self.getSymbolFromId(msg.tickerId) if symb: #print "[{1}] {0}: {2}".format(symb, fieldType[msg.field], msg.size) db.tickers.update({"symbol": symb}, {"$set": {TickType.getField(msg.field): msg.size}}, upsert = True)
def on_session_createdSeries(self, key, field): """ Signal handler called when new Series objects are created. @param key id of ticker with new series @param field series field """ if key != self.key: return series = self.collection[self.key].series[field] self.addSeries(TickType.getField(field), series) self.controlsTree.sortByColumn(0, Qt.AscendingOrder)
def tickOptionComputation(cls, tickerId, field, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta, undPrice): toAdd = "id=" + tickerId + " " + TickType.getField(field) + ": vol = " + (impliedVol if impliedVol >= 0 and (impliedVol != float('inf')) else "N/A") + " delta = " + (delta if abs(delta) <= 1 else "N/A") + " gamma = " + (gamma if abs(gamma) <= 1 else "N/A") + " vega = " + (vega if abs(vega) <= 1 else "N/A") + " theta = " + (theta if abs(theta) <= 1 else "N/A") + " optPrice = " + (optPrice if optPrice >= 0 and (optPrice != float('inf')) else "N/A") + " pvDividend = " + (pvDividend if pvDividend >= 0 and (pvDividend != float('inf')) else "N/A") + " undPrice = " + (undPrice if undPrice >= 0 and (undPrice != float('inf')) else "N/A") return toAdd
def tickOptionComputation(cls, tickerId, field, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta, undPrice): """ generated source for method tickOptionComputation """ toAdd = "id=" + str(tickerId) + " " + TickType.getField(field) \ + ": vol = " + (str(impliedVol) if (impliedVol >= 0 and impliedVol != Double.MAX_VALUE) else "N/A") \ + " delta = " + (str(delta) if (abs(delta) <= 1) else "N/A") \ + " gamma = " + (str(gamma) if (abs(gamma) <= 1) else "N/A") \ + " vega = " + (str(vega) if (abs(vega) <= 1) else "N/A") \ + " theta = " + (str(theta) if (abs(theta) <= 1) else "N/A") \ + " optPrice = " + (str(optPrice) if (optPrice >= 0 and optPrice != Double.MAX_VALUE) else "N/A") \ + " pvDividend = " + (str(pvDividend) if (pvDividend >= 0 and pvDividend != Double.MAX_VALUE) else "N/A") \ + " undPrice = " + (str(undPrice) if (undPrice >= 0 and undPrice != Double.MAX_VALUE) else "N/A") return toAdd
def tickPriceHandler(self, msg): """Handle TickPrice messages from IB. Remove the globals and implement a Producer/Consumer @param msg ib.opt.message.TickPrice Message sent by IB """ self.ticks[msg.tickerId] = msg symb = self.getSymbolFromId(msg.tickerId) if symb: db.tickers.update({"symbol": symb}, {"$set": {TickType.getField(msg.field): msg.price}}, upsert = True) self.event.set()
def my_callback_handler(msg): #for reference on this /home/deep/development/IbPy/ib/ext/TickType #another class method tt.getField(msg.field) if msg.field in [tt.BID,tt.ASK,tt.LAST,tt.HIGH,tt.LOW,tt.OPEN,tt.CLOSE]: print tt.getField(msg.field), msg.price elif msg.field in [tt.BID_SIZE,tt.ASK_SIZE,tt.LAST_SIZE,tt.VOLUME,tt.AVG_VOLUME]: print tt.getField(msg.field), msg.size elif msg.field in [tt,LAST_TIMESTAMP]: print tt.getField(msg.field), msg.time
def on_tick(self, msg): ''' Callback for market data requests ''' tick_id = msg.tickerId if msg.typeName == 'tickSize': field_name = TickType.getField(msg.field) value = msg.size elif msg.typeName == 'tickPrice': field_name = TickType.getField(msg.field) value = msg.price elif msg.typeName in ['tickGeneric', 'tickString']: field_name = TickType.getField(msg.tickType) value = msg.value if tick_id in self.print_once: if tick_id not in self.ticker_data: ticker_data = dict() else: ticker_data = self.ticker_data[tick_id] ticker_data[field_name] = value self.ticker_data[tick_id] = ticker_data elif tick_id in self.tick_callbacks: self.tick_callbacks[tick_id](field_name, value)
def handle_tick_size(self, msg): if self.enable_ticker: self.output('%s %d %s %d' % (repr(msg), msg.field, TickType().getField( msg.field), msg.size)) symbol = self.symbols_by_id[msg.tickerId] if msg.field == 0: # bid_size symbol.bid_size = msg.size if self.enable_ticker: symbol.update_quote() elif msg.field == 3: # ask_size symbol.ask_size = msg.size if self.enable_ticker: symbol.update_quote() elif msg.field == 5: # last_size symbol.size = msg.size elif msg.field == 8: # volume symbol.volume = msg.size if self.enable_ticker: symbol.update_trade()
def handle_tick_price(self, msg): for cb in self.addsymbol_callbacks: if str(cb.id.ticker_id) == str(msg.tickerId): cb.complete(True) if self.enable_ticker: self.output('%s %d %s %s' % (repr(msg), msg.field, TickType().getField( msg.field), msg.price)) symbol = self.symbols_by_id[msg.tickerId] if msg.field == 1: # bid symbol.bid = msg.price if self.enable_ticker: symbol.update_quote() elif msg.field == 2: # ask symbol.ask = msg.price if self.enable_ticker: symbol.update_quote() elif msg.field == 4: # last symbol.last = msg.price elif msg.field == 9: # close symbol.close = msg.price
def tickOptionComputation(cls, tickerId, field, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta, undPrice): toAdd = "id=" + tickerId + " " + TickType.getField( field) + ": vol = " + ( impliedVol if impliedVol >= 0 and (impliedVol != float('inf')) else "N/A") + " delta = " + ( delta if abs(delta) <= 1 else "N/A") + " gamma = " + ( gamma if abs(gamma) <= 1 else "N/A") + " vega = " + ( vega if abs(vega) <= 1 else "N/A") + " theta = " + (theta if abs( theta) <= 1 else "N/A") + " optPrice = " + ( optPrice if optPrice >= 0 and (optPrice != float('inf')) else "N/A") + " pvDividend = " + ( pvDividend if pvDividend >= 0 and (pvDividend != float('inf')) else "N/A" ) + " undPrice = " + ( undPrice if undPrice >= 0 and (undPrice != float('inf')) else "N/A") return toAdd
def __init__(self, tws, symbol, client_id): self.tws = tws self.output = tws.output self.ticktype = TickType() self.clients = set([client_id]) self.ticker_id = tws.next_id() self.symbol = symbol self.bid = 0.0 self.bid_size = 0 self.ask = 0.0 self.ask_size = 0 self.last = 0.0 self.size = 0 self.volume = 0 self.close = 0.0 self.tws.symbols[symbol] = self self.last_quote = '' self.tws.symbols_by_id[self.ticker_id] = self contract = self.tws.create_contract(symbol, 'STK', 'SMART', 'SMART', 'USD') self.output('TWS_Symbol %s %s created for client %s' % (self, symbol, client_id)) self.output('reqMktData(%d, %s)' % (self.ticker_id, symbol)) self.tws.tws_conn.reqMktData(self.ticker_id, contract, '', False)
def tickPrice(cls, tickerId, field, price, canAutoExecute): return "id=" + tickerId + " " + TickType.getField(field) + "=" + price + " " + " canAutoExecute" if (canAutoExecute != 0) else " noAutoExecute"
def tickStringHandler(self,msg): if Debug: print(msg) print('['+TickType.getField(msg.TickType)+']: ',msg.value)
def tickSize(cls, tickerId, field, size): return "id=" + tickerId + " " + TickType.getField(field) + "=" + size
def tickStringHandler(self, msg): print "STRING--- [{2}] {0}: {1}.".format( TickType.getField(msg.tickType), msg.value, self.getSymbolFromId(msg.tickerId))
def tickGenericHandler(self, msg): print "GENERIC--- [{2}] {0}: {1}.".format( TickType.getField(msg.tickType), msg.value, self.getSymbolFromId(msg.tickerId))
def tickSize(cls, tickerId, field, size): """ generated source for method tickSize """ return "id=" + str(tickerId) + " " + TickType.getField( field) + "=" + str(size)
def tickStringHandler(self, msg): if Debug: print(msg) print('[' + TickType.getField(msg.TickType) + ']: ', msg.value)
def tickString(cls, tickerId, tickType, value): """ generated source for method tickString """ return "id=" + str(tickerId) + " " + TickType.getField(tickType) + "=" + str(value)
def tickString(cls, tickerId, tickType, value): return "id=" + tickerId + " " + TickType.getField(tickType) + "=" + value
def tickPrice(cls, tickerId, field, price, canAutoExecute): return "id=" + tickerId + " " + TickType.getField( field) + "=" + price + " " + " canAutoExecute" if ( canAutoExecute != 0) else " noAutoExecute"
def handle_tick_string(self, msg): if self.enable_ticker: self.output('%s %d %s %s' % (repr(msg), msg.tickType, TickType().getField( msg.tickType), msg.value))
def tickSizeHandler(self,msg): if Debug: print(msg) print('['+TickType.getField(msg.field)+']: ',msg.size) self.mkt_data.generic_data.update({TickType.getField(msg.field):msg.size})
def tickSize(cls, tickerId, field, size): """ generated source for method tickSize """ return "id=" + str(tickerId) + " " + TickType.getField(field) + "=" + str(size)
def my_callback_handler(msg): if msg.field in [tt.BID, tt.ASK, tt.LAST]: # now w e can just store the response in the data frame contracts.loc[msg.tickerId, tt.getField(msg.field)] = msg.price
def tickEFP(cls, tickerId, tickType, basisPoints, formattedBasisPoints, impliedFuture, holdDays, futureExpiry, dividendImpact, dividendsToExpiry): return "id=" + tickerId + " " + TickType.getField( tickType ) + ": basisPoints = " + basisPoints + "/" + formattedBasisPoints + " impliedFuture = " + impliedFuture + " holdDays = " + holdDays + " futureExpiry = " + futureExpiry + " dividendImpact = " + dividendImpact + " dividends to expiry = " + dividendsToExpiry
def tickPrice(cls, tickerId, field, price, canAutoExecute): """ generated source for method tickPrice """ return "id=" + str(tickerId) + " " + TickType.getField(field) + "=" + str(price) + " " + (" canAutoExecute" if (canAutoExecute != 0) else " noAutoExecute")
def tickString(cls, tickerId, tickType, value): """ generated source for method tickString """ return "id=" + str(tickerId) + " " + TickType.getField( tickType) + "=" + str(value)
def tickString(cls, tickerId, tickType, value): return "id=" + tickerId + " " + TickType.getField( tickType) + "=" + value
def tickPrice(cls, tickerId, field, price, canAutoExecute): """ generated source for method tickPrice """ return "id=" + str(tickerId) + " " + TickType.getField( field) + "=" + str(price) + " " + (" canAutoExecute" if (canAutoExecute != 0) else " noAutoExecute")
def tickSizeHandler(self, msg): if Debug: print(msg) print('[' + TickType.getField(msg.field) + ']: ', msg.size) self.mkt_data.generic_data.update( {TickType.getField(msg.field): msg.size})