def nextValidId(self, orderId): """ OrderId orderId """ logger.info("next valid id %s" % orderId) if not self.next_order_id or orderId > self.next_order_id: self.next_order_id = orderId
def init(self): logger.info("importing data") self.app_context.start() self.app_config = self.app_context.app_config self.feed = self.app_context.provider_mgr.get(self.app_config.feed_id) self.feed.start(self.app_context)
def import_inst_from_ib(broker, symbol, sec_type='STK', exchange=None, currency=None): try: result = AsyncResult() logger.info("importing symbol %s" % symbol) broker.reqContractDetails(symbol=symbol, sec_type=sec_type, exchange=exchange, currency=currency, callback=result) # broker.reqScannerSubscription(inst_type='STK', location_code='STK.US', scan_code='TOP_PERC_GAIN', above_vol=1000000, callback=callback) logger.info("done %s %s" % (symbol, result.get(timeout=3))) except Exception as e: logger.error("faile to import %s", symbol, e)
def on_bar(self, bar): if self.buy_order is None and self.ema_fast.now('value') > self.ema_slow.now('value'): self.buy_order = self.market_order(inst_id=bar.inst_id, action=OrdAction.BUY, qty=self.qty) logger.info("%s,B,%s,%s,%.2f,%.2f,%.2f" % ( bar.timestamp, self.buy_order.cl_id, self.buy_order.cl_ord_id, bar.close, self.ema_fast.now('value'), self.ema_slow.now('value'))) elif self.buy_order is not None and self.ema_fast.now('value') < self.ema_slow.now('value'): sell_order = self.market_order(inst_id=bar.inst_id, action=OrdAction.SELL, qty=self.qty) logger.info("%s,S,%s,%s,%.2f,%.2f,%.2f" % ( bar.timestamp, sell_order.cl_id, sell_order.cl_ord_id, bar.close, self.ema_fast.now('value'), self.ema_slow.now('value')))
def run(self): self.instruments = self.app_context.ref_data_mgr.get_insts(self.app_config.instrument_ids) if isinstance(self.app_config, HistoricalMarketDataImporterConfig): self.subscript_market_data(self.feed, self.instruments, self.app_config.subscription_types, self.app_config.from_date, self.app_config.to_date) else: self.subscript_market_data(self.feed, self.instruments, self.app_config.subscription_types) logger.info("ATS started, presss Ctrl-C to stop") for i in xrange(1, 1000): time.sleep(1) logger.info(".")
def init(self): logger.info("starting ATS") self.app_config = self.app_config self.app_context = ApplicationContext(app_config=self.app_config) self.app_context.start() self.portfolio = self.app_context.portf_mgr.get_or_new_portfolio(self.app_config.portfolio_id, self.app_config.portfolio_initial_cash) self.app_context.add_startable(self.portfolio) self.strategy = self.app_context.stg_mgr.get_or_new_stg(self.app_config) self.app_context.add_startable(self.strategy)
def create_database(self): logger.info("creating keyspace") statement = CassandraDataStore.create_keyspace_cql % self.cass_config.keyspace logger.info(statement) self.session.execute(statement, timeout=30) self.session.set_keyspace(self.cass_config.keyspace) cql_path = os.path.abspath(os.path.join(os.path.dirname(__file__), self.cass_config.cql_script_path)) logger.info("creating table %s" % cql_path) with open(cql_path) as cql_file: for stmt in cql_file.read().split(";"): if len(stmt.strip()) > 0: logger.info(stmt) self.session.execute(stmt, timeout=30) logger.info("table created")
def init(self): logger.info("starting ATS") self.app_config = self.app_config self.app_context = ApplicationContext(app_config=self.app_config) self.app_context.start() self.portfolio = self.app_context.portf_mgr.get_or_new_portfolio( self.app_config.portfolio_id, self.app_config.portfolio_initial_cash) self.app_context.add_startable(self.portfolio) self.strategy = self.app_context.stg_mgr.get_or_new_stg( self.app_config) self.app_context.add_startable(self.strategy)
def on_bar(self, bar): ratio = self.vix_close.now('value') / self.vxv_close.now('close') # what is order is not filled and there is signal again? if self.order is None: # long XIV at the close when VIX index closed below the VXV index # long XIV when ratio < 0.92 if ratio < self.threshold[0]: logger.info("%s,B,%.2f" % (bar.timestamp, bar.close)) if bar.inst_id == self.xiv.id(): self.order = self.market_order(inst_id=bar.inst_id, action=OrdAction.BUY, qty=self.qty) # long VXX when ratio > 1.08 elif ratio > self.threshold[1]: logger.info("%s,B,%.2f" % (bar.timestamp, bar.close)) if bar.inst_id == self.vxx.id(): self.order = self.market_order(inst_id=bar.inst_id, action=OrdAction.BUY, qty=self.qty)
def run(self): self.instruments = self.app_context.ref_data_mgr.get_insts( self.app_config.instrument_ids) if isinstance(self.app_config, HistoricalMarketDataImporterConfig): self.subscript_market_data(self.feed, self.instruments, self.app_config.subscription_types, self.app_config.from_date, self.app_config.to_date) else: self.subscript_market_data(self.feed, self.instruments, self.app_config.subscription_types) logger.info("ATS started, presss Ctrl-C to stop") for i in xrange(1, 1000): time.sleep(1) logger.info(".")
def on_bar(self, bar): if self.buy_order is None and self.ema_fast.now( 'value') > self.ema_slow.now('value'): self.buy_order = self.market_order(inst_id=bar.inst_id, action=OrdAction.BUY, qty=self.qty) logger.info( "%s,B,%s,%s,%.2f,%.2f,%.2f" % (bar.timestamp, self.buy_order.cl_id, self.buy_order.cl_ord_id, bar.close, self.ema_fast.now('value'), self.ema_slow.now('value'))) elif self.buy_order is not None and self.ema_fast.now( 'value') < self.ema_slow.now('value'): sell_order = self.market_order(inst_id=bar.inst_id, action=OrdAction.SELL, qty=self.qty) logger.info("%s,S,%s,%s,%.2f,%.2f,%.2f" % (bar.timestamp, sell_order.cl_id, sell_order.cl_ord_id, bar.close, self.ema_fast.now('value'), self.ema_slow.now('value')))
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_exec_report(self, exec_report): logger.info(exec_report)
def on_new_ord_req(self, order): logger.info("[%s] %s" % (self.__class__.__name__, order)) return order
def on_ord_upd(self, ord_upd): logger.info(ord_upd)
def run(self): self.strategy.start(self.app_context) logger.info("ATS started, presss Ctrl-C to stop")
def _start(self, app_context, **kwargs): self.__server = zerorpc.Server(self) self.__server.bind(self.__address) logger.info("starting OMS") self.__server.run()
def on_trade(self, trade): logger.info(trade)
def save_trade(self, trade): logger.info("[%s] saving %s" % (self.__class__.__name__, trade)) id, packed = self._serialize(trade) self.trades.update({'_id': id}, packed, upsert=True)
def remove_database(self): logger.info("dropping keyspace") self.session.execute(CassandraDataStore.drop_keyspace_cql % self.cass_config.keyspace)
def save_bar(self, bar): logger.info("[%s] saving %s" % (self.__class__.__name__, bar)) id, packed = self._serialize(bar) self.bars.update({'_id': id}, packed, upsert=True)
def save_currency(self, currency): logger.info("[%s] saving %s" % (self.__class__.__name__, currency)) id, packed = self._serialize(currency) self.currencies.update({'_id': id}, packed, upsert=True)
def save_time_series(self, timeseries): logger.info("[%s] saving %s" % (self.__class__.__name__, timeseries)) id, packed = self._serialize(timeseries) self.time_series.update({'_id': id}, packed, upsert=True)
def save_instrument(self, instrument): logger.info("[%s] saving %s" % (self.__class__.__name__, instrument)) id, packed = self._serialize(instrument) self.instruments.update({'_id': id}, packed, upsert=True)
def scannerDataEnd(self, reqId): logger.info("scannerDataEnd, reqId=%s", reqId) self._complete_req(reqId)
def scannerData(self, reqId, rank, contractDetails, distance, benchmark, projection, legsStr): logger.info( "scannerData, reqId=%s, rank=%s, contractDetails=%s, distance=%s, benchmark=%s, projection=%s, legsStr=%s", reqId, rank, contractDetails, distance, benchmark, projection, legsStr)
def on_bar(self, bar): logger.info(bar)
def on_quote(self, quote): logger.info(quote)
def save_exchange(self, exchange): logger.info("[%s] saving %s" % (self.__class__.__name__, exchange)) id, packed = self._serialize(exchange) self.exchanges.update({'_id': id}, packed, upsert=True)
def on_market_depth(self, market_depth): logger.info(market_depth)
def contractDetailsEnd(self, reqId): logger.info("contractDetailsEnd, reqId=%s" % reqId) self._complete_req(reqId)