def __process_event(self, event): logger.debug("[%s] %s" % (self.__class__.__name__, event)) if event.inst_id in self.ord_req_map: for cl_ord_map in self.ord_req_map[event.inst_id].values(): for new_ord_req in cl_ord_map.values(): fill_info = self.fill_strategy.process_w_market_data(new_ord_req, event, False) executed = self.execute(new_ord_req, fill_info)
def updateMktDepthL2(self, id, position, marketMaker, operation, side, price, size): """ TickerId id, int position, IBString marketMaker, int operation, int side, double price, int size """ logger.debug("updateMktDepthL2, id=%s position=%s marketMaker=%s operation=%s side=%s price=%s size=%s", id, position, marketMaker, operation, side, price, size)
def on_trade(self, trade): logger.debug("[%s] %s" % (self.__class__.__name__, trade)) self.__trade_dict[trade.inst_id] = trade self.get_series(trade.series_id()).add({"timestamp": trade.timestamp, "price": trade.price, "size": trade.size}) if self._is_realtime_persist(): self.store.save_trade(trade)
def tickOptionComputation(self, tickerId, tickType, impliedVol, delta, optPrice, gamma, vega, theta, undPrice): """ TickerId tickerId, TickType tickType, double impliedVol, double delta, double optPrice, double pvDividend, double gamma, double vega, double theta, double undPrice """ logger.debug( "tickOptionComputation, tickerId=%s tickType=%s simpliedVol=%s delta=%s optPrice=%s, gamma=%s, vega=%s, theta=%s, undPrice=%s", tickerId, tickType, impliedVol, delta, optPrice, gamma, vega, theta, undPrice)
def scannerData(self, reqId, rank, contractDetails, distance, benchmark, projection, legsStr): """ int reqId, int rank, ContractDetails contractDetails, IBString const & distance, IBString const & benchmark, IBString const & projection, IBString const & legsStr """ logger.debug( "scannerData, reqId=%s, rank=%s, contractDetails=%s, distance=%s, benchmark=%s, projection=%s, legsStr=%s", reqId, rank, contractDetails, distance, benchmark, projection, legsStr)
def realtimeBar(self, reqId, time, open, high, low, close, volume, wap, count): """ TickerId reqId, long time, double open, double high, double low, double close, long volume, double wap, int count """ logger.debug("realtimeBar, reqId=%s time=%s open=%s high=%s low=%s close=%s volume=%s wap=%s count=%s", reqId, time, open, high, low, close, volume, wap, count)
def on_new_ord_req(self, new_ord_req): logger.debug("[%s] %s" % (self.__class__.__name__, new_ord_req)) self.clordid_ordid_map self.__add_order(new_ord_req) self.__send_exec_report(new_ord_req, 0, 0, OrdStatus.SUBMITTED) fill_info = self.fill_strategy.process_new_order(new_ord_req) executed = self.execute(new_ord_req, fill_info)
def updateMktDepthL2(self, id, position, marketMaker, operation, side, price, size): """ TickerId id, int position, IBString marketMaker, int operation, int side, double price, int size """ logger.debug( "updateMktDepthL2, id=%s position=%s marketMaker=%s operation=%s side=%s price=%s size=%s", id, position, marketMaker, operation, side, price, size)
def orderStatus(self, id, status, filled, remaining, avgFillPrice, permId, parentId, lastFilledPrice, clientId, whyHeld): """ OrderId orderId, IBString const & status, int filled, int remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId, IBString const & whyHeld """ logger.debug( "orderStatus, id=%s, status=%s, filled=%s, remaining=%s, avgFillPrice=%s, permId=%s, parentId=%s, lastFilledPrice=%s, clientId=%s, whyHeld=%s", id, status, filled, remaining, avgFillPrice, permId, parentId, lastFilledPrice, clientId, whyHeld)
def on_quote(self, quote): logger.debug("[%s] %s" % (self.__class__.__name__, quote)) self.__quote_dict[quote.inst_id] = quote self.get_series(quote.series_id()).add( {"timestamp": quote.timestamp, "bid": quote.bid, "ask": quote.ask, "bid_size": quote.bid_size, "ask_size": quote.ask_size}) if self._is_realtime_persist(): self.store.save_quote(quote)
def updatePortfolio(self, contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName): """ Contract contract, int position, double marketPrice, double marketValue, double averageCost, double unrealizedPNL, double realizedPNL, IBString const & accountName """ logger.debug( "updatePortfolio, contract=%s position=%s marketPrice=%s marketValue=%s averageCost=%s, unrealizedPNL=%s, realizedPNL=%s, accountName=%s", contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName)
def historicalData(self, reqId, date, open, high, low, close, volume, barCount, WAP, hasGaps): """ TickerId reqId, IBString const & date, double open, double high, double low, double close, int volume, int barCount, double WAP, int hasGaps) """ logger.debug( "historicalData, reqId=%s date=%s open=%s high=%s low=%s close=%s volume=%s barCount=%s WAP=%s hasGaps=%s", reqId, date, open, high, low, close, volume, barCount, WAP, hasGaps)
def on_new_ord_req(self, new_ord_req): logger.debug("[%s] %s" % (self.__class__.__name__, new_ord_req)) ord_id = self.get_next_order_id() self.ord_req_reg.add_ord_req(ord_id, new_ord_req) ib_order = self.model_factory.create_ib_order(new_ord_req) contract = self.model_factory.create_ib_contract(new_ord_req.inst_id) self.tws.placeOrder(ord_id, contract, ib_order)
def on_ord_cancel_req(self, ord_cancel_req): logger.debug("[%s] %s" % (self.__class__.__name__, ord_cancel_req)) ord_id = self.ord_req_reg.get_ord_id(cl_id=ord_cancel_req.cl_id, cl_ord_id=ord_cancel_req.cl_ord_id) if ord_id: self.tws.cancelOrder(ord_id) else: logger.error( "cannot find old order, cl_id = %s, cl_ord_id = %s" % (ord_cancel_req.cl_id, ord_cancel_req.cl_ord_id))
def on_bar(self, bar): logger.debug("[%s] %s" % (self.__class__.__name__, bar)) self.__bar_dict[bar.inst_id] = bar self.get_series(bar.series_id()).add( {"timestamp": bar.timestamp, "open": bar.open, "high": bar.high, "low": bar.low, "close": bar.close, "vol": bar.vol}) if self._is_realtime_persist(): self.store.save_bar(bar)
def process_row(self, index, row): logger.debug("[%s] process_row with index %s, symbol %s" % (self.__class__.__name__, index, row['Symbol'])) inst = self.ref_data_mgr.get_inst(symbol=row['Symbol']) return Bar(inst_id=inst.inst_id, timestamp=DateUtils.datetime_to_unixtimemillis(index), open=row['Open'], high=row['High'], low=row['Low'], close=row['Close'], vol=row['Volume'], size=row['BarSize'])
def on_update(self, data): logger.debug("[%s] on_update %s" % (self.__class__.__name__, data)) if data['timestamp'] != self.__curr_timestamp: self.__curr_timestamp = data['timestamp'] self._flush_and_create() data_name = data['name'] if data_name in self.input_names: j = self.input_names_pos[data_name] self.cache[data_name] = self.inputs[j].get_by_idx( keys=self.input_keys, idx=slice(-self.length, None, None))
def tickEFP(self, tickerId, tickType, basisPoints, formattedBasisPoints, totalDividends, holdDays, futureExpiry, dividendImpact, dividendsToExpiry): """ EWrapper self, TickerId tickerId, TickType tickType, double basisPoints, IBString const & formattedBasisPoints, double totalDividends, int holdDays, IBString const & futureExpiry, double dividendImpact, double dividendsToExpiry """ logger.debug( "tickEFP, tickerId=%s tickType=%s basisPoints=%s formattedBasisPoints=%s totalDividends=%s, holdDays=%s, futureExpiry=%s, dividendImpact=%s, dividendsToExpiry=%s", tickerId, tickType, basisPoints, formattedBasisPoints, totalDividends, holdDays, futureExpiry, dividendImpact, dividendsToExpiry)
def on_trade(self, trade): logger.debug("[%s] %s" % (self.__class__.__name__, trade)) self.__trade_dict[trade.inst_id] = trade self.get_series(trade.series_id()).add({ "timestamp": trade.timestamp, "price": trade.price, "size": trade.size }) if self._is_realtime_persist(): self.store.save_trade(trade)
def send_order(self, new_ord_req): logger.debug("[%s] %s" % (self.__class__.__name__, new_ord_req)) if new_ord_req.cl_id in self.ord_reqs and new_ord_req.cl_ord_id in self.ord_reqs[new_ord_req.cl_id]: raise RuntimeError("ord_reqs[%s][%s] already exist" % (new_ord_req.cl_id, new_ord_req.cl_ord_id)) self._add_order_req(new_ord_req) order = self.app_context.order_mgr.send_order(new_ord_req) self._add_order(order) self.get_position(order.inst_id).add_order(order) return order
def on_quote(self, quote): logger.debug("[%s] %s" % (self.__class__.__name__, quote)) self.__quote_dict[quote.inst_id] = quote self.get_series(quote.series_id()).add({ "timestamp": quote.timestamp, "bid": quote.bid, "ask": quote.ask, "bid_size": quote.bid_size, "ask_size": quote.ask_size }) if self._is_realtime_persist(): self.store.save_quote(quote)
def on_exec_report(self, exec_report): logger.debug("[%s] %s" % (self.__class__.__name__, exec_report)) if exec_report.cl_id not in self.ord_reqs and exec_report.cl_ord_id not in self.ord_reqs[exec_report.cl_id]: raise Exception("Order not found, ord_reqs[%s][%s]" % (exec_report.cl_id, exec_report.cl_ord_id)) new_ord_req = self.ord_reqs[exec_report.cl_id][exec_report.cl_ord_id] direction = 1 if new_ord_req.action == OrdAction.BUY else -1 if exec_report.last_qty > 0: inst = self.app_context.ref_data_mgr.get_inst(exec_report.inst_id) multiplier = inst.factor if inst.type in [InstType.Future, InstType.Option] else 1 self.cash -= (direction * multiplier* exec_report.last_qty * exec_report.last_price + exec_report.commission) self.add_position(exec_report.inst_id, exec_report.cl_id, exec_report.cl_ord_id, direction * exec_report.last_qty) self.update_position_price(exec_report.timestamp, exec_report.inst_id, multiplier*exec_report.last_price)
def on_bar(self, bar): logger.debug("[%s] %s" % (self.__class__.__name__, bar)) self.__bar_dict[bar.inst_id] = bar self.get_series(bar.series_id()).add({ "timestamp": bar.timestamp, "open": bar.open, "high": bar.high, "low": bar.low, "close": bar.close, "vol": bar.vol }) if self._is_realtime_persist(): self.store.save_bar(bar)
def on_ord_replace_req(self, ord_replace_req): logger.debug("[%s] %s" % (self.__class__.__name__, ord_replace_req)) existing_ord_req = self.ord_req_reg.get_ord_req(cl_id=ord_replace_req.cl_id, cl_ord_id=ord_replace_req.cl_ord_id) if existing_ord_req: ord_id = self.ord_req_reg.get_ord_id(cl_id=ord_replace_req.cl_id, cl_ord_id=ord_replace_req.cl_ord_id) updated_ord_req = existing_ord_req.update_ord_request(ord_replace_req) self.ord_req_reg.add_ord_req(ord_id, updated_ord_req) ib_order = self.model_factory.create_ib_order(updated_ord_req) contract = self.model_factory.create_ib_contract(updated_ord_req.inst_id) self.tws.placeOrder(ord_id, contract, ib_order) else: logger.error("cannot find old order, cl_ord_id = %s" % ord_replace_req.cl_ord_id)
def contractDetails(self, reqId, contractDetails): """ int reqId, ContractDetails contractDetails """ cd = contractDetails sd = contractDetails.summary logger.debug("contractDetails, reqId=%s, conId=%s, symbol=%s, secType=%s, exchange=%s, " + "primaryExchange=%s, expiry=%s, strike=%s, right=%s, " + "multiplier=%s, currency=%s, localSymbol=%s, secIdType=%s, " + "secId=%s, includeExpired=%s, comboLegsDescrip=%s, comboLegs=%s, " + "underComp=%s, " + "marketName=%s, tradingClass=%s, minTick=%s, orderTypes=%s, " + "validExchanges=%s, priceMagnifier=%s, underConId=%s, longName=%s, " + "longName=%s, contractMonth=%s, industry=%s, category=%s, " + "timeZoneId=%s, tradingHours=%s, liquidHours=%s, evRule=%s, " + "evMultiplier=%s, secIdList=%s, cusip=%s, ratings=%s, " + "descAppend=%s, bondType=%s, couponType=%s, callable=%s, " + "putable=%s, coupon=%s, convertible=%s, issueDate=%s, " + "nextOptionDate=%s, nextOptionType=%s, nextOptionPartial=%s, notes=%s" , reqId, sd.conId, sd.symbol, sd.secType, sd.exchange, sd.primaryExchange, sd.expiry, sd.strike, sd.right, sd.multiplier, sd.currency, sd.localSymbol, sd.secIdType, sd.secId, sd.includeExpired, sd.comboLegsDescrip, sd.comboLegs, sd.underComp, cd.marketName, cd.tradingClass, cd.minTick, cd.orderTypes, cd.validExchanges, cd.priceMagnifier, cd.underConId, cd.longName, cd.longName, cd.contractMonth, cd.industry, cd.category, cd.timeZoneId, cd.tradingHours, cd.liquidHours, cd.evRule, cd.evMultiplier, cd.secIdList, cd.cusip, cd.ratings, cd.descAppend, cd.bondType, cd.couponType, cd.callable, cd.putable, cd.coupon, cd.convertible, cd.issueDate, cd.nextOptionDate, cd.nextOptionType, cd.nextOptionPartial, cd.notes) self.ref_data_mgr.create_inst(name=cd.longName, type=sd.secType, symbol=sd.symbol, exch_id=sd.exchange, ccy_id=sd.currency, # alt_symbol = {Broker.IB: sd.symbol}, # alt_exch_id = {Broker.IB: sd.exchange}, sector=cd.industry, industry=cd.category) logger.info("saved")
def on_new_ord_req(self, new_ord_req): logger.debug("[%s] %s" % (self.__class__.__name__, new_ord_req)) self.send_order(new_ord_req)
def on_market_depth(self, market_depth): logger.debug("[%s] %s" % (self.__class__.__name__, market_depth))
def on_trade(self, trade): logger.debug("[%s] %s" % (self.__class__.__name__, trade)) self.update_time(trade.timestamp)
def on_quote(self, quote): logger.debug("[%s] %s" % (self.__class__.__name__, quote)) self.update_time(quote.timestamp)
def tickGeneric(self, tickerId, tickType, value): """ TickerId tickerId, TickType tickType, double value """ logger.debug("tickGeneric, tickerId=%s tickType=%s value=%s", tickerId, tickType, value)
def on_ord_upd(self, ord_upd): logger.debug("[%s] %s" % (self.__class__.__name__, ord_upd))
def on_ord_upd(self, ord_upd): if ord_upd.portf_id == self.portf_id: logger.debug("[%s] %s" % (self.__class__.__name__, ord_upd))
def replace_order(self, ord_replace_req): logger.debug("[%s] %s" % (self.__class__.__name__, ord_replace_req)) order = self.app_context.order_mgr.replace_order(ord_replace_req) return order
def cancel_order(self, ord_cancel_req): logger.debug("[%s] %s" % (self.__class__.__name__, ord_cancel_req)) order = self.app_context.order_mgr.cancel_order(ord_cancel_req) return order
def nextValidId(self, orderId): """ OrderId orderId """ logger.debug("nextValidId, orderId=%s", orderId)
def on_ord_replace_req(self, ord_replace_req): logger.debug("[%s] %s" % (self.__class__.__name__, ord_replace_req)) self.replace_order(ord_replace_req)
def on_acc_upd(self, acc_upd): logger.debug("[%s] %s" % (self.__class__.__name__, acc_upd))
def on_ord_cancel_req(self, ord_cancel_req): logger.debug("[%s] %s" % (self.__class__.__name__, ord_cancel_req)) self.cancel_order(ord_cancel_req)
def tickString(self, tickerId, tickType, value): """ TickerId tickerId, TickType tickType, IBString const & value """ logger.debug("tickString, tickerId=%s tickType=%s value=%s", tickerId, tickType, value)
def on_exec_report(self, exec_report): logger.debug("[%s] %s" % (self.__class__.__name__, exec_report))
def on_bar(self, bar): logger.debug("[%s] %s" % (self.__class__.__name__, bar)) self.update_time(bar.timestamp)
def on_portf_upd(self, portf_upd): logger.debug("[%s] %s" % (self.__class__.__name__, portf_upd))
def tickSize(self, tickerId, field, size): logger.debug("tickSize, tickerId=%s field=%s size=%s", tickerId, field, size)
def on_bar(self, bar): reval_date = DateUtils.unixtimemillis_to_datetime(bar.timestamp) futures_expiry_dict = VIXFuture.future_expirydays_calculator(reval_date, self.instruments) active_futures = {k: v for k, v in futures_expiry_dict.iteritems() if v > self.exp_date_lb and v < self.exp_date_ub} active_futures_sorted = OrderedDict(sorted(active_futures.items(), key=lambda y: y[1])) if bar.inst_id in active_futures_sorted: logger.debug("id is in active futures" % bar.inst_id) roll = VIXFuture.daily_roll(bar.adj_close, self.vix_index.now("value"), active_futures_sorted[bar.inst_id]) logger.debug("roll = %s" % roll) if not self.portfolio.has_position(self.stg_id, bar.inst_id): threshold = self.get_stg_config_value("short_entry_threshold", 0.02) if roll > threshold: logger.debug("Roll > threshold %s" % threshold) logger.debug("Now send a short order") self.market_order(inst_id=bar.inst_id, action=OrdAction.SELL, qty=self.qty) else: threshold = self.get_stg_config_value("short_exit_threshold", -0.01) if roll < threshold: logger.debug("Roll < threshold %s" % threshold) logger.debug("Now exit") self.market_order(inst_id=bar.inst_id, action=OrdAction.BUY, qty=self.qty)
def receiveFA(self, pFaDataType, cxml): """ faDataType pFaDataType, IBString const & cxml """ logger.debug("receiveFA, pFaDataType=%s, cxml=%s", pFaDataType, cxml)