Example #1
0
 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 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)
Example #4
0
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)
Example #5
0
 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(".")
Example #7
0
    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)
Example #8
0
    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")
Example #9
0
    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(".")
Example #12
0
 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 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)
Example #14
0
    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")
Example #15
0
 def on_exec_report(self, exec_report):
     logger.info(exec_report)
Example #16
0
 def on_new_ord_req(self, order):
     logger.info("[%s] %s" % (self.__class__.__name__, order))
     return order
Example #17
0
 def on_ord_upd(self, ord_upd):
     logger.info(ord_upd)
Example #18
0
    def run(self):
        self.strategy.start(self.app_context)

        logger.info("ATS started, presss Ctrl-C to stop")
Example #19
0
 def _start(self, app_context, **kwargs):
     self.__server = zerorpc.Server(self)
     self.__server.bind(self.__address)
     logger.info("starting OMS")
     self.__server.run()
Example #20
0
 def on_trade(self, trade):
     logger.info(trade)
Example #21
0
 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)
Example #22
0
 def remove_database(self):
     logger.info("dropping keyspace")
     self.session.execute(CassandraDataStore.drop_keyspace_cql % self.cass_config.keyspace)
Example #23
0
 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)
Example #24
0
 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)
Example #25
0
 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)
Example #26
0
 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)
Example #27
0
 def scannerDataEnd(self, reqId):
     logger.info("scannerDataEnd, reqId=%s", reqId)
     self._complete_req(reqId)
Example #28
0
 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)
Example #29
0
 def on_bar(self, bar):
     logger.info(bar)
Example #30
0
 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)
Example #31
0
 def on_quote(self, quote):
     logger.info(quote)
Example #32
0
 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)
Example #33
0
 def on_market_depth(self, market_depth):
     logger.info(market_depth)
Example #34
0
 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)
Example #35
0
 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)
Example #36
0
    def run(self):
        self.strategy.start(self.app_context)

        logger.info("ATS started, presss Ctrl-C to stop")
Example #37
0
 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)
Example #38
0
 def contractDetailsEnd(self, reqId):
     logger.info("contractDetailsEnd, reqId=%s" % reqId)
     self._complete_req(reqId)
Example #39
0
 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)
Example #40
0
 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)