How to use the rqalpha.utils.exception.patch_user_exc function in rqalpha

To help you get started, we’ve selected a few rqalpha examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ricequant / rqalpha / rqalpha / mod / rqalpha_mod_sys_benchmark / mod.py View on Github external
def _validate_benchmark(bechmark_order_book_id, env):
        instrument = env.data_proxy.instruments(bechmark_order_book_id)
        if instrument is None:
            raise patch_user_exc(ValueError(_(u"invalid benchmark {}").format(bechmark_order_book_id)))

        if instrument.order_book_id == "000300.XSHG":
            # 000300.XSHG 数据进行了补齐,因此认为只要benchmark设置了000300.XSHG,就存在数据,不受限于上市日期。
            return

        config = env.config
        start_date = config.base.start_date
        end_date = config.base.end_date
        if instrument.listed_date.date() > start_date:
            raise patch_user_exc(ValueError(
                _(u"benchmark {benchmark} has not been listed on {start_date}").format(benchmark=bechmark_order_book_id,
                                                                                       start_date=start_date)))
        if instrument.de_listed_date.date() < end_date:
            if config.base.run_type == RUN_TYPE.BACKTEST:
                msg = _(u"benchmark {benchmark} has been de_listed on {end_date}").format(
                    benchmark=bechmark_order_book_id,
github ricequant / rqalpha / rqalpha / mod / rqalpha_mod_sys_simulation / mod.py View on Github external
def start_up(self, env, mod_config):

        if env.config.base.run_type == RUN_TYPE.LIVE_TRADING:
            return

        mod_config.matching_type = self.parse_matching_type(mod_config.matching_type)

        if env.config.base.margin_multiplier <= 0:
            raise patch_user_exc(ValueError(_(u"invalid margin multiplier value: value range is (0, +∞]")))

        if env.config.base.frequency == "tick":
            mod_config.volume_limit = False
            if mod_config.matching_type not in [
                MATCHING_TYPE.NEXT_TICK_LAST,
                MATCHING_TYPE.NEXT_TICK_BEST_OWN,
                MATCHING_TYPE.NEXT_TICK_BEST_COUNTERPARTY,
            ]:
                raise RuntimeError(_("Not supported matching type {}").format(mod_config.matching_type))
        else:
            if mod_config.matching_type not in [
                MATCHING_TYPE.NEXT_BAR_OPEN,
                MATCHING_TYPE.CURRENT_BAR_CLOSE,
            ]:
                raise RuntimeError(_("Not supported matching type {}").format(mod_config.matching_type))
github ricequant / rqalpha / rqalpha / mod / rqalpha_mod_sys_simulation / simulation_event_source.py View on Github external
def _get_universe(self):
        universe = self._env.get_universe()
        if len(universe) == 0 and DEFAULT_ACCOUNT_TYPE.STOCK.name not in self._config.base.accounts:
            raise patch_user_exc(RuntimeError(_(
                "Current universe is empty. Please use subscribe function before trade"
            )), force=True)
        return universe
github ricequant / rqalpha / rqalpha / model / bar.py View on Github external
instrument = self._data_proxy.instruments(key)
        if instrument is None:
            raise patch_user_exc(ValueError('invalid order book id or symbol: {}'.format(key)))
        order_book_id = instrument.order_book_id

        try:
            return self._cache[order_book_id]
        except KeyError:
            try:
                if not self._dt:
                    return BarObject(instrument, NANDict, self._dt)
                bar = self._data_proxy.get_bar(order_book_id, self._dt, self._frequency)
            except Exception as e:
                system_log.exception(e)
                raise patch_user_exc(KeyError(_(u"id_or_symbols {} does not exist").format(key)))
            if bar is None:
                return BarObject(instrument, NANDict, self._dt)
            else:
                self._cache[order_book_id] = bar
                return bar
github ricequant / rqalpha / rqalpha / execution_context.py View on Github external
def wrapper(*args, **kwargs):
                phase = cls.stack.top.phase
                if phase not in phases:
                    raise patch_user_exc(
                        RuntimeError(_(u"You cannot call %s when executing %s") % (func.__name__, phase.value)))
                return func(*args, **kwargs)
            return wrapper
github ricequant / rqalpha / rqalpha / model / bar.py View on Github external
def __getitem__(self, key):
        if not isinstance(key, six.string_types):
            raise patch_user_exc(ValueError('invalid key {} (use order_book_id please)'.format(key)))

        instrument = self._data_proxy.instruments(key)
        if instrument is None:
            raise patch_user_exc(ValueError('invalid order book id or symbol: {}'.format(key)))
        order_book_id = instrument.order_book_id

        try:
            return self._cache[order_book_id]
        except KeyError:
            try:
                if not self._dt:
                    return BarObject(instrument, NANDict, self._dt)
                bar = self._data_proxy.get_bar(order_book_id, self._dt, self._frequency)
            except Exception as e:
                system_log.exception(e)
                raise patch_user_exc(KeyError(_(u"id_or_symbols {} does not exist").format(key)))
            if bar is None:
                return BarObject(instrument, NANDict, self._dt)
            else:
                self._cache[order_book_id] = bar
github ricequant / rqalpha / rqalpha / utils / scheduler.py View on Github external
def run_weekly(self, func, weekday=None, tradingday=None, time_rule=None):
        _verify_function('run_weekly', func)
        if (weekday is not None and tradingday is not None) or (weekday is None and tradingday is None):
            raise patch_user_exc(ValueError('select one of weekday/tradingday'))

        if weekday is not None:
            if weekday < 1 or weekday > 7:
                raise patch_user_exc(ValueError('invalid weekday, should be in [1, 7]'))
            day_checker = lambda: self._is_weekday(weekday - 1)
        else:
            if tradingday > 5 or tradingday < -5 or tradingday == 0:
                raise patch_user_exc(ValueError('invalid trading day, should be in [-5, 0), (0, 5]'))
            if tradingday > 0:
                tradingday -= 1
            day_checker = lambda: self._is_nth_trading_day_in_week(tradingday)

        time_checker = self._time_rule_for(time_rule)

        self._registry.append((day_checker, time_checker, func))
github ricequant / rqalpha / rqalpha / utils / strategy_loader_help.py View on Github external
def compile_strategy(source_code, strategy, scope):
    try:
        code = compile(source_code, strategy, 'exec')
        six.exec_(code, scope)
        return scope
    except Exception as e:
        exc_type, exc_val, exc_tb = sys.exc_info()
        exc_val = patch_user_exc(exc_val, force=True)
        try:
            msg = str(exc_val)
        except Exception as e1:
            msg = ""
            six.print_(e1)

        error = CustomError()
        error.set_msg(msg)
        error.set_exc(exc_type, exc_val, exc_tb)
        stackinfos = list(traceback.extract_tb(exc_tb))

        if isinstance(e, (SyntaxError, IndentationError)):
            error.add_stack_info(exc_val.filename, exc_val.lineno, "", exc_val.text)
        else:
            for item in stackinfos:
                filename, lineno, func_name, code = item
github ricequant / rqalpha / rqalpha / utils / scheduler.py View on Github external
def _verify_function(name, func):
    if not callable(func):
        raise patch_user_exc(ValueError('scheduler.{}: func should be callable'.format(name)))
    sig = signature(func)
    if len(sig.parameters) != 2:
        raise patch_user_exc(TypeError(
            'scheduler.{}: func should take exactly 2 arguments (context, bar_dict)'.format(name)))