How to use rqalpha - 10 common examples

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_simulation / matcher.py View on Github external
if self._price_limit:
                    if order.side == SIDE.BUY and deal_price >= price_board.get_limit_up(order_book_id):
                        reason = _(
                            "Order Cancelled: current bar [{order_book_id}] reach the limit_up price."
                        ).format(order_book_id=order.order_book_id)
                        order.mark_rejected(reason)
                        continue
                    if order.side == SIDE.SELL and deal_price <= price_board.get_limit_down(order_book_id):
                        reason = _(
                            "Order Cancelled: current bar [{order_book_id}] reach the limit_down price."
                        ).format(order_book_id=order.order_book_id)
                        order.mark_rejected(reason)
                        continue
                if self._liquidity_limit:
                    if order.side == SIDE.BUY and price_board.get_a1(order_book_id) == 0:
                        reason = _(
                            "Order Cancelled: [{order_book_id}] has no liquidity."
                        ).format(order_book_id=order.order_book_id)
                        order.mark_rejected(reason)
                        continue
                    if order.side == SIDE.SELL and price_board.get_b1(order_book_id) == 0:
                        reason = _(
                            "Order Cancelled: [{order_book_id}] has no liquidity."
                        ).format(order_book_id=order.order_book_id)
                        order.mark_rejected(reason)
                        continue

            if self._volume_limit:
                bar = self._env.bar_dict[order_book_id]
                volume_limit = round(bar.volume * self._volume_percent) - self._turnover[order.order_book_id]
                round_lot = instrument.round_lot
                volume_limit = (volume_limit // round_lot) * round_lot
github ricequant / rqalpha / tests / unittest / test_model / test_booking.py View on Github external
"old_quantity": 1, "today_quantity": 3
                }},
            "short_positions": {
                "TF1812": {
                    "today_quantity": 4
                }
            }
        }).encode('utf-8'))

        self.assertPositions({
            (POSITION_DIRECTION.LONG, "RB1812", 3, 1),
            (POSITION_DIRECTION.SHORT, "TF1812", 4, 0)
        })

        self.env.event_bus.publish_event(Event(EVENT.TRADE, trade=Trade.__from_create__(
            0, 0, 2, SIDE.SELL, POSITION_EFFECT.OPEN, "RB1812"
        )))
        self.assertPositions({
            (POSITION_DIRECTION.LONG, "RB1812", 3, 1),
            (POSITION_DIRECTION.SHORT, "RB1812", 2, 0),
            (POSITION_DIRECTION.SHORT, "TF1812", 4, 0)
        })
        self.env.event_bus.publish_event(Event(EVENT.TRADE, trade=Trade.__from_create__(
            0, 0, 3, SIDE.SELL, POSITION_EFFECT.CLOSE, "RB1812"
        )))
        self.assertPositions({
            (POSITION_DIRECTION.LONG, "RB1812", 1, 0),
            (POSITION_DIRECTION.SHORT, "RB1812", 2, 0),
            (POSITION_DIRECTION.SHORT, "TF1812", 4, 0)
        })

        with self.mock_data_proxy_method("instruments", mock_get_instrument):
github ricequant / rqalpha / rqalpha / main.py View on Github external
user_strategy = Strategy(env.event_bus, scope, ucontext, should_run_init)
        env.user_strategy = user_strategy

        if (should_resume and not should_run_init) or not should_resume:
            with run_with_user_log_disabled(disabled=should_resume):
                user_strategy.init()

        if config.extra.context_vars:
            for k, v in six.iteritems(config.extra.context_vars):
                if isinstance(v, RqAttrDict):
                    v = v.__dict__
                setattr(ucontext, k, v)

        if persist_helper:
            env.event_bus.publish_event(Event(EVENT.BEFORE_SYSTEM_RESTORED))
            env.event_bus.publish_event(Event(EVENT.DO_RESTORE))
            env.event_bus.publish_event(Event(EVENT.POST_SYSTEM_RESTORED))

        init_succeed = True

        if should_resume and should_run_init:
            user_strategy.init()

        executor.run(bar_dict)

        if env.profile_deco:
            output_profile_result(env)
    except CustomException as e:
        if init_succeed and persist_helper and env.config.base.persist_mode == const.PERSIST_MODE.ON_CRASH:
            persist_helper.persist()
github ricequant / rqalpha / rqalpha / strategy.py View on Github external
before_trading = self._user_before_trading
        handle_bar = self._user_handle_bar

        exchange_on_dt_change = simu_exchange.on_dt_change
        exchange_on_bar_close = simu_exchange.on_bar_close
        exchange_on_day_open = simu_exchange.on_day_open
        exchange_on_day_close = simu_exchange.on_day_close
        exchange_update_portfolio = simu_exchange.update_portfolio

        is_show_progress_bar = self.trading_params.show_progress

        def on_dt_change(dt):
            self._current_dt = dt
            exchange_on_dt_change(dt)

        with ExecutionContext(self, EXECUTION_PHASE.INIT):
            init(strategy_context)

        try:
            for dt, event in self._event_source:
                on_dt_change(dt)

                bar_dict = BarMap(dt, self.current_universe, data_proxy)

                if event == EVENT_TYPE.DAY_START:
                    with ExecutionContext(self, EXECUTION_PHASE.BEFORE_TRADING, bar_dict):
                        exchange_on_day_open()
                        before_trading(strategy_context, None)

                elif event == EVENT_TYPE.HANDLE_BAR:
                    with ExecutionContext(self, EXECUTION_PHASE.HANDLE_BAR, bar_dict):
                        exchange_update_portfolio(bar_dict)
github ricequant / rqalpha / rqalpha / mod / rqalpha_mod_sys_analyser / plot.py View on Github external
def _(txt):
        return gettext(txt) if use_chinese_fonts else txt
github ricequant / rqalpha / rqalpha / mod / rqalpha_mod_sys_simulation / simulation_event_source.py View on Github external
def _get_day_bar_dt(self, date):
        if self._env.config.base.market == MARKET.CN:
            return date.replace(hour=15, minute=0)
        elif self._env.config.base.market == MARKET.HK:
            return date.replace(hour=16, minute=0)
        else:
            raise NotImplementedError(_("Unsupported market {}".format(self._env.config.base.market)))
github ricequant / rqalpha / rqalpha / mod / risk_manager / frontend_validator.py View on Github external
if bar.isnan:
            """
            只有未上市/已退市,对应的bar才为NaN
            """
            instrument = env.get_instrument(order_book_id)
            if trading_date < instrument.listed_date.date():
                order._mark_rejected(_(u"Order Rejected: {order_book_id} is not listed!").format(
                    order_book_id=order_book_id,
                ))
            elif trading_date > instrument.de_listed_date.date():
                order._mark_rejected(_(u"Order Rejected: {order_book_id} has been delisted!").format(
                    order_book_id=order_book_id,
                ))
            else:
                order._mark_rejected(_(u"Order Rejected: {order_book_id} is not trading!").format(
                    order_book_id=order_book_id,
                ))
            return False
        elif not bar.is_trading:
            """
            如果bar.is_trading为False,还需要判断是否为停盘,如果不是停牌,则说明交易量为0.
            """
            if bar.suspended:
                order._mark_rejected(_(u"Order Rejected: {order_book_id} is suspended!").format(
                    order_book_id=order_book_id,
                ))
                return False
        return True
github ricequant / rqalpha / rqalpha / utils / arg_checker.py View on Github external
def _are_valid_query_entities(self, func_name, entities):
        from sqlalchemy.orm.attributes import InstrumentedAttribute
        for e in entities:
            if not isinstance(e, InstrumentedAttribute):
                raise RQInvalidArgument(
                    _(u"function {}: invalid {} argument, should be entity like "
                      u"Fundamentals.balance_sheet.total_equity, got {} (type: {})").format(
                        func_name, self.arg_name, e, type(e)
                    ))
github ricequant / rqalpha / rqalpha / mod / rqalpha_mod_sys_accounts / api / api_future.py View on Github external
def order(id_or_ins, amount, side, position_effect, style):
    if not isinstance(style, OrderStyle):
        raise RuntimeError
    if amount < 0:
        raise RuntimeError
    if amount == 0:
        user_system_log.warn(_(u"Order Creation Failed: Order amount is 0."))
        return None
    if isinstance(style, LimitOrder) and style.get_limit_price() <= 0:
        raise RQInvalidArgument(_(u"Limit order price should be positive"))

    order_book_id = assure_future_order_book_id(id_or_ins)
    env = Environment.get_instance()
    if env.config.base.run_type != RUN_TYPE.BACKTEST:
        if "88" in order_book_id:
            raise RQInvalidArgument(_(u"Main Future contracts[88] are not supported in paper trading."))
        if "99" in order_book_id:
            raise RQInvalidArgument(_(u"Index Future contracts[99] are not supported in paper trading."))

    price = env.get_last_price(order_book_id)
    if not is_valid_price(price):
        user_system_log.warn(
            _(u"Order Creation Failed: [{order_book_id}] No market data").format(order_book_id=order_book_id)
        )
        return

    amount = int(amount)

    env = Environment.get_instance()

    orders = []
    if position_effect == POSITION_EFFECT.CLOSE:
github ricequant / rqalpha / rqalpha / utils / config.py View on Github external
def parse_run_type(rt_str):
    assert isinstance(rt_str, six.string_types)
    mapping = {
        "b": RUN_TYPE.BACKTEST,
        "p": RUN_TYPE.PAPER_TRADING,
        "r": RUN_TYPE.LIVE_TRADING,
    }
    try:
        return mapping[rt_str]
    except KeyError:
        raise RuntimeError(_(u"unknown run type: {}").format(rt_str))