Esempio n. 1
0
class PlotStore(object):
    def __init__(self, env):
        # type: (Environment) -> None
        self._env = env
        self._plots = defaultdict(dict)

    def add_plot(self, dt, series_name, value):
        self._plots[series_name][dt] = value

    def get_plots(self):
        return self._plots

    @ExecutionContext.enforce_phase(EXECUTION_PHASE.ON_BAR,
                                    EXECUTION_PHASE.ON_TICK,
                                    EXECUTION_PHASE.SCHEDULED)
    @apply_rules(
        verify_that("series_name", pre_check=True).is_instance_of(str),
        verify_that("value", pre_check=True).is_number(),
    )
    def plot(self, series_name, value):
        # type: (str, float) -> None
        """
        在生成的图标结果中,某一个根线上增加一个点。

        :param series_name: 序列名称
        :param value: 值
        """
        self.add_plot(self._env.trading_dt.date(), series_name, value)
Esempio n. 2
0
def subscribe(id_or_symbols):
    """
    订阅合约行情。该操作会导致合约池内合约的增加,从而影响handle_bar中处理bar数据的数量。

    需要注意,用户在初次编写策略时候需要首先订阅合约行情,否则handle_bar不会被触发。

    :param id_or_ins: 标的物
    :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]
    """
    current_universe = Environment.get_instance().get_universe()
    if isinstance(id_or_symbols, six.string_types):
        order_book_id = instruments(id_or_symbols).order_book_id
        current_universe.add(order_book_id)
    elif isinstance(id_or_symbols, Instrument):
        current_universe.add(id_or_symbols.order_book_id)
    elif isinstance(id_or_symbols, Iterable):
        for item in id_or_symbols:
            current_universe.add(assure_order_book_id(item))
    else:
        raise RQInvalidArgument(_(u"unsupported order_book_id type"))
    verify_that('id_or_symbols')._are_valid_instruments("subscribe", id_or_symbols)
    Environment.get_instance().update_universe(current_universe)
Esempio n. 3
0
def subscribe(id_or_symbols):
    """
    订阅合约行情。该操作会导致合约池内合约的增加,从而影响handle_bar中处理bar数据的数量。

    需要注意,用户在初次编写策略时候需要首先订阅合约行情,否则handle_bar不会被触发。

    :param id_or_ins: 标的物
    :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]
    """
    current_universe = Environment.get_instance().get_universe()
    if isinstance(id_or_symbols, six.string_types):
        order_book_id = instruments(id_or_symbols).order_book_id
        current_universe.add(order_book_id)
    elif isinstance(id_or_symbols, Instrument):
        current_universe.add(id_or_symbols.order_book_id)
    elif isinstance(id_or_symbols, Iterable):
        for item in id_or_symbols:
            current_universe.add(assure_order_book_id(item))
    else:
        raise RQInvalidArgument(_(u"unsupported order_book_id type"))
    verify_that('id_or_symbols')._are_valid_instruments("subscribe", id_or_symbols)
    Environment.get_instance().update_universe(current_universe)
Esempio n. 4
0
class PlotStore(object):
    def __init__(self, env):
        # type: (Environment) -> None
        self._env = env
        self._plots = defaultdict(dict)

    def add_plot(self, dt, series_name, value):
        self._plots[series_name][dt] = value

    def get_plots(self):
        return self._plots

    @ExecutionContext.enforce_phase(
        EXECUTION_PHASE.ON_BAR, EXECUTION_PHASE.ON_TICK, EXECUTION_PHASE.SCHEDULED
    )
    @apply_rules(
        verify_that("series_name", pre_check=True).is_instance_of(str),
        verify_that("value", pre_check=True).is_number(),
    )
    def plot(self, series_name, value):
        # type: (str, float) -> None
        """
        在策略运行结束后的收益图中,加入自定义的曲线。
        每次调用 plot 函数将会以当前时间为横坐标,value 为纵坐标加入一个点,series_name 相同的点将连成一条曲线。

        :param series_name: 曲线名称
        :param value: 点的纵坐标值

        :example:

        .. code-block:: python

            def handle_bar(context, bar_dict):
                plot("OPEN", bar_dict["000001.XSHE"].open)

        """
        self.add_plot(self._env.trading_dt.date(), series_name, value)
Esempio n. 5
0
def subscribe(id_or_symbols):
    # type: (Union[str, Instrument, Iterable[str], Iterable[Instrument]]) -> None

    """
    订阅合约行情。该操作会导致合约池内合约的增加,从而影响handle_bar中处理bar数据的数量。

    需要注意,用户在初次编写策略时候需要首先订阅合约行情,否则handle_bar不会被触发。

    :param id_or_symbols: 标的物

    """
    current_universe = Environment.get_instance().get_universe()
    if isinstance(id_or_symbols, six.string_types):
        order_book_id = instruments(id_or_symbols).order_book_id
        current_universe.add(order_book_id)
    elif isinstance(id_or_symbols, Instrument):
        current_universe.add(id_or_symbols.order_book_id)
    elif isinstance(id_or_symbols, Iterable):
        for item in id_or_symbols:
            current_universe.add(assure_order_book_id(item))
    else:
        raise RQInvalidArgument(_(u"unsupported order_book_id type"))
    verify_that("id_or_symbols")._are_valid_instruments("subscribe", id_or_symbols)
    Environment.get_instance().update_universe(current_universe)
Esempio n. 6
0
    if order is None:
        patch_user_exc(KeyError(_(u"Cancel order fail: invalid order id")))
    env = Environment.get_instance()
    if env.can_cancel_order(order):
        env.broker.cancel_order(order)
    return order


@export_as_api
@ExecutionContext.enforce_phase(EXECUTION_PHASE.ON_INIT,
                                EXECUTION_PHASE.BEFORE_TRADING,
                                EXECUTION_PHASE.ON_BAR,
                                EXECUTION_PHASE.ON_TICK,
                                EXECUTION_PHASE.AFTER_TRADING,
                                EXECUTION_PHASE.SCHEDULED)
@apply_rules(verify_that('id_or_symbols').are_valid_instruments())
def update_universe(id_or_symbols):
    """
    该方法用于更新现在关注的证券的集合(e.g.:股票池)。PS:会在下一个bar事件触发时候产生(新的关注的股票池更新)效果。并且update_universe会是覆盖(overwrite)的操作而不是在已有的股票池的基础上进行增量添加。比如已有的股票池为['000001.XSHE', '000024.XSHE']然后调用了update_universe(['000030.XSHE'])之后,股票池就会变成000030.XSHE一个股票了,随后的数据更新也只会跟踪000030.XSHE这一个股票了。

    :param id_or_ins: 标的物
    :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]
    """
    if isinstance(id_or_symbols, (six.string_types, Instrument)):
        id_or_symbols = [id_or_symbols]
    order_book_ids = set(
        assure_order_book_id(order_book_id) for order_book_id in id_or_symbols)
    if order_book_ids != Environment.get_instance().get_universe():
        Environment.get_instance().update_universe(order_book_ids)

def symbol(order_book_id, split=", "):
    if isinstance(order_book_id, six.string_types):
        return "{}[{}]".format(order_book_id,
                               instruments(order_book_id).symbol)
    else:
        s = split.join(symbol(item) for item in order_book_id)
        return s


def now_time_str(str_format="%H:%M:%S"):
    return Environment.get_instance().trading_dt.strftime(str_format)


@export_as_api
@apply_rules(verify_that('quantity').is_number())
def order(order_book_id, quantity, price=None, style=None):
    """
    全品种通用智能调仓函数

    如果不指定 price, 则相当于下 MarketOrder

    如果 order_book_id 是股票,等同于调用 order_shares

    如果 order_book_id 是期货,则进行智能下单:

        *   quantity 表示调仓量
        *   如果 quantity 为正数,则先平 Sell 方向仓位,再开 Buy 方向仓位
        *   如果 quantity 为负数,则先平 Buy 反向仓位,再开 Sell 方向仓位

    :param order_book_id: 下单标的物
Esempio n. 8
0
def export_as_api(func):
    __all__.append(func.__name__)

    func = decorate_api_exc(func)

    return func


@export_as_api
@ExecutionContext.enforce_phase(EXECUTION_PHASE.ON_BAR,
                                EXECUTION_PHASE.ON_TICK,
                                EXECUTION_PHASE.SCHEDULED,
                                EXECUTION_PHASE.GLOBAL)
@apply_rules(
    verify_that('id_or_ins').is_valid_stock(),
    verify_that('amount').is_number(),
    verify_that('style').is_instance_of((MarketOrder, LimitOrder, type(None))))
def order_shares(id_or_ins, amount, price=None, style=None):
    """
    落指定股数的买/卖单,最常见的落单方式之一。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。

    :param id_or_ins: 下单标的物
    :type id_or_ins: :class:`~Instrument` object | `str`

    :param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。

    :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。

    :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder`
    :type style: `OrderStyle` object
Esempio n. 9
0
from rqalpha.model.instrument import Instrument
from rqalpha.model.order import MarketOrder, LimitOrder, OrderStyle, Order
from rqalpha.utils.arg_checker import apply_rules, verify_that
from rqalpha.utils.functools import instype_singledispatch


@export_as_api
@ExecutionContext.enforce_phase(
    EXECUTION_PHASE.OPEN_AUCTION,
    EXECUTION_PHASE.ON_BAR,
    EXECUTION_PHASE.ON_TICK,
    EXECUTION_PHASE.SCHEDULED,
    EXECUTION_PHASE.GLOBAL
)
@apply_rules(
    verify_that('amount').is_number(),
    verify_that('style').is_instance_of((MarketOrder, LimitOrder, type(None)))
)
@instype_singledispatch
def order_shares(id_or_ins, amount, price=None, style=None):
    # type: (Union[str, Instrument], int, Optional[float], Optional[OrderStyle]) -> Optional[Order]
    """
    指定股数的买/卖单,最常见的落单方式之一。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。

    :param id_or_ins: 下单标的物
    :param amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。
    :param price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。
    :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder`

    :example:

def export_as_api(func):
    __all__.append(func.__name__)

    func = decorate_api_exc(func)

    return func


@ExecutionContext.enforce_phase(EXECUTION_PHASE.ON_BAR,
                                EXECUTION_PHASE.ON_TICK,
                                EXECUTION_PHASE.SCHEDULED,
                                EXECUTION_PHASE.GLOBAL)
@apply_rules(
    verify_that('id_or_ins').is_valid_future(),
    verify_that('amount').is_greater_or_equal_than(0),
    verify_that('side').is_in([SIDE.BUY, SIDE.SELL]),
    verify_that('position_effect').is_in(
        [POSITION_EFFECT.OPEN, POSITION_EFFECT.CLOSE]),
    verify_that('style').is_instance_of((LimitOrder, MarketOrder, type(None))))
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"))
Esempio n. 11
0
@export_as_api
def symbol(order_book_id, split=", "):
    if isinstance(order_book_id, six.string_types):
        return "{}[{}]".format(order_book_id,
                               instruments(order_book_id).symbol)
    else:
        s = split.join(symbol(item) for item in order_book_id)
        return s


def now_time_str(str_format="%H:%M:%S"):
    return Environment.get_instance().trading_dt.strftime(str_format)


@export_as_api
@apply_rules(verify_that("quantity").is_number())
def order(order_book_id, quantity, price=None, style=None):
    """
    全品种通用智能调仓函数

    如果不指定 price, 则相当于下 MarketOrder

    如果 order_book_id 是股票,等同于调用 order_shares

    如果 order_book_id 是期货,则进行智能下单:

        *   quantity 表示调仓量
        *   如果 quantity 为正数,则先平 Sell 方向仓位,再开 Buy 方向仓位
        *   如果 quantity 为负数,则先平 Buy 反向仓位,再开 Sell 方向仓位

    :param order_book_id: 下单标的物
Esempio n. 12
0
def symbol(order_book_id, split=", "):
    if isinstance(order_book_id, six.string_types):
        return "{}[{}]".format(order_book_id,
                               instruments(order_book_id).symbol)
    else:
        s = split.join(symbol(item) for item in order_book_id)
        return s


def now_time_str(str_format="%H:%M:%S"):
    return Environment.get_instance().trading_dt.strftime(str_format)


@export_as_api
@apply_rules(verify_env().portfolio_exists(),
             verify_that('quantity').is_number())
def order(order_book_id, quantity, price=None, style=None):
    """
    全品种通用智能调仓函数

    如果不指定 price, 则相当于下 MarketOrder

    如果 order_book_id 是股票,等同于调用 order_shares

    如果 order_book_id 是期货,则进行智能下单:

        *   quantity 表示调仓量
        *   如果 quantity 为正数,则先平 Sell 方向仓位,再开 Buy 方向仓位
        *   如果 quantity 为负数,则先平 Buy 反向仓位,再开 Sell 方向仓位

    :param order_book_id: 下单标的物
Esempio n. 13
0
from rqalpha import export_as_api
from rqalpha.utils.i18n import gettext as _

from . import mod_name


@export_as_api
def get_positions(booking=None):
    env = Environment.get_instance()
    mod = env.mod_dict[mod_name]
    booking_account = mod.booking_account
    return booking_account.get_positions(booking)


@export_as_api
@apply_rules(verify_that('direction').is_in([POSITION_DIRECTION.LONG, POSITION_DIRECTION.SHORT]))
def get_position(order_book_id, direction, booking=None):
    env = Environment.get_instance()
    mod = env.mod_dict[mod_name]
    booking_account = mod.booking_account
    return booking_account.get_position(order_book_id, direction, booking)


@export_as_api
@apply_rules(
    verify_that('id_or_ins').is_valid_future(),
    verify_that('amount').is_number().is_greater_or_equal_than(0),
    verify_that('side').is_in([SIDE.BUY, SIDE.SELL]),
    verify_that('position_effect').is_in([POSITION_EFFECT.OPEN, POSITION_EFFECT.CLOSE, POSITION_EFFECT.CLOSE_TODAY]),
    verify_that('style').is_instance_of((LimitOrder, MarketOrder, type(None))))
def send_order(order_book_id, amount, side, position_effect, style):
Esempio n. 14
0
    EXECUTION_PHASE.ON_TICK,
    EXECUTION_PHASE.AFTER_TRADING,
    EXECUTION_PHASE.SCHEDULED,
)
def get_open_orders():
    """
    获取当日未成交订单数据

    :return: List[:class:`~Order` object]
    """
    return Environment.get_instance().broker.get_open_orders()


@export_as_api
@apply_rules(
    verify_that("id_or_ins").is_valid_instrument(),
    verify_that("amount").is_number().is_greater_than(0),
    verify_that("side").is_in([SIDE.BUY, SIDE.SELL]),
)
def submit_order(id_or_ins, amount, side, price=None, position_effect=None):
    """
    通用下单函数,策略可以通过该函数自由选择参数下单。

    :param id_or_ins: 下单标的物
    :type id_or_ins: :class:`~Instrument` object | `str`

    :param float amount: 下单量,需为正数

    :param side: 多空方向,多(SIDE.BUY)或空(SIDE.SELL)
    :type side: :class:`~SIDE` enum
Esempio n. 15
0
                         cal_style(price, style))


@sell_close.register(INSTRUMENT_TYPE.FUTURE)
def future_sell_close(id_or_ins,
                      amount,
                      price=None,
                      style=None,
                      close_today=False):
    position_effect = POSITION_EFFECT.CLOSE_TODAY if close_today else POSITION_EFFECT.CLOSE
    return _submit_order(id_or_ins, amount, SIDE.SELL, position_effect,
                         cal_style(price, style))


@export_as_api
@apply_rules(verify_that('underlying_symbol').is_instance_of(str))
def get_future_contracts(underlying_symbol):
    # type: (str) -> List[str]
    """
    获取某一期货品种在策略当前日期的可交易合约order_book_id列表。按照到期月份,下标从小到大排列,返回列表中第一个合约对应的就是该品种的近月合约。

    :param underlying_symbol: 期货合约品种,例如沪深300股指期货为'IF'

    :example:

    获取某一天的主力合约代码(策略当前日期是20161201):

        ..  code-block:: python

            [In]
            logger.info(get_future_contracts('IF'))
Esempio n. 16
0
@export_as_api
def symbol(order_book_id, split=", "):
    if isinstance(order_book_id, six.string_types):
        return "{}[{}]".format(order_book_id, instruments(order_book_id).symbol)
    else:
        s = split.join(symbol(item) for item in order_book_id)
        return s


def now_time_str(str_format="%H:%M:%S"):
    return Environment.get_instance().trading_dt.strftime(str_format)


@export_as_api
@apply_rules(verify_that('quantity').is_number())
def order(order_book_id, quantity, price=None, style=None):
    """
    全品种通用智能调仓函数

    如果不指定 price, 则相当于下 MarketOrder

    如果 order_book_id 是股票,等同于调用 order_shares

    如果 order_book_id 是期货,则进行智能下单:

        *   quantity 表示调仓量
        *   如果 quantity 为正数,则先平 Sell 方向仓位,再开 Buy 方向仓位
        *   如果 quantity 为负数,则先平 Buy 反向仓位,再开 Sell 方向仓位

    :param order_book_id: 下单标的物
Esempio n. 17
0
from rqalpha.utils.i18n import gettext as _

from . import mod_name


@export_as_api
def get_positions(booking=None):
    env = Environment.get_instance()
    mod = env.mod_dict[mod_name]
    booking_account = mod.booking_account
    return booking_account.get_positions(booking)


@export_as_api
@apply_rules(
    verify_that('direction').is_in(
        [POSITION_DIRECTION.LONG, POSITION_DIRECTION.SHORT]))
def get_position(order_book_id, direction, booking=None):
    env = Environment.get_instance()
    mod = env.mod_dict[mod_name]
    booking_account = mod.booking_account
    return booking_account.get_position(order_book_id, direction, booking)


@export_as_api
@apply_rules(
    verify_that('id_or_ins').is_valid_future(),
    verify_that('amount').is_number().is_greater_or_equal_than(0),
    verify_that('side').is_in([SIDE.BUY, SIDE.SELL]),
    verify_that('position_effect').is_in([
        POSITION_EFFECT.OPEN, POSITION_EFFECT.CLOSE,
        POSITION_EFFECT.CLOSE_TODAY
Esempio n. 18
0
export_as_api(market_close)
export_as_api(market_open)
export_as_api(industry_code, name='industry_code')
export_as_api(sector_code, name='sector_code')


@export_as_api
@ExecutionContext.enforce_phase(
    EXECUTION_PHASE.OPEN_AUCTION,
    EXECUTION_PHASE.ON_BAR,
    EXECUTION_PHASE.ON_TICK,
    EXECUTION_PHASE.SCHEDULED,
    EXECUTION_PHASE.GLOBAL
)
@apply_rules(verify_that('id_or_ins').is_valid_stock(),
             verify_that('amount').is_number(),
             verify_that('style').is_instance_of((MarketOrder, LimitOrder, type(None))))
def order_shares(id_or_ins, amount, price=None, style=None):
    # type: (Union[str, Instrument], int, Optional[float], Optional[OrderStyle]) -> Optional[Order]
    """
    指定股数的买/卖单,最常见的落单方式之一。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。

    :param id_or_ins: 下单标的物
    :param amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。
    :param price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。
    :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder`

    :example:

    .. code-block:: python
Esempio n. 19
0

def export_as_api(func):
    __all__.append(func.__name__)

    func = decorate_api_exc(func)

    return func


@export_as_api
@ExecutionContext.enforce_phase(EXECUTION_PHASE.ON_BAR,
                                EXECUTION_PHASE.ON_TICK,
                                EXECUTION_PHASE.SCHEDULED,
                                EXECUTION_PHASE.GLOBAL)
@apply_rules(verify_that('id_or_ins').is_valid_stock(),
             verify_that('amount').is_number(),
             verify_that('style').is_instance_of((MarketOrder, LimitOrder, type(None))))
def order_shares(id_or_ins, amount, price=None, style=None):
    """
    落指定股数的买/卖单,最常见的落单方式之一。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。

    :param id_or_ins: 下单标的物
    :type id_or_ins: :class:`~Instrument` object | `str`

    :param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。

    :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。

    :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder`
    :type style: `OrderStyle` object
Esempio n. 20
0
                                EXECUTION_PHASE.ON_BAR,
                                EXECUTION_PHASE.ON_TICK,
                                EXECUTION_PHASE.AFTER_TRADING,
                                EXECUTION_PHASE.SCHEDULED)
def get_open_orders():
    """
    获取当日未成交订单数据

    :return: List[:class:`~Order` object]
    """
    return Environment.get_instance().broker.get_open_orders()


@export_as_api
@apply_rules(
    verify_that("id_or_ins").is_valid_instrument(),
    verify_that("amount").is_number().is_greater_than(0),
    verify_that("side").is_in([SIDE.BUY, SIDE.SELL])
)
def submit_order(id_or_ins, amount, side, price=None, position_effect=None):

    order_book_id = assure_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."))
    style = cal_style(price, None)
    market_price = env.get_last_price(order_book_id)
    if not is_valid_price(market_price):
Esempio n. 21
0
__all__ = [
]


def export_as_api(func):
    __all__.append(func.__name__)

    func = decorate_api_exc(func)

    return func


@ExecutionContext.enforce_phase(EXECUTION_PHASE.ON_BAR,
                                EXECUTION_PHASE.ON_TICK,
                                EXECUTION_PHASE.SCHEDULED)
@apply_rules(verify_that('id_or_ins').is_valid_future(),
             verify_that('amount').is_greater_or_equal_than(0),
             verify_that('side').is_in([SIDE.BUY, SIDE.SELL]),
             verify_that('position_effect').is_in([POSITION_EFFECT.OPEN, POSITION_EFFECT.CLOSE]),
             verify_that('style').is_instance_of((LimitOrder, MarketOrder, type(None))))
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"))
Esempio n. 22
0
    EXECUTION_PHASE.ON_TICK,
    EXECUTION_PHASE.AFTER_TRADING,
    EXECUTION_PHASE.SCHEDULED,
)
def get_open_orders():
    # type: () -> List[Order]
    """
    获取当日未成交订单数据
    """
    broker = Environment.get_instance().broker
    return [o for o in broker.get_open_orders() if o.position_effect != POSITION_EFFECT.EXERCISE]


@export_as_api
@apply_rules(
    verify_that("id_or_ins").is_valid_instrument(),
    verify_that("amount").is_number().is_greater_than(0),
    verify_that("side").is_in([SIDE.BUY, SIDE.SELL]),
)
def submit_order(id_or_ins, amount, side, price=None, position_effect=None):
    # type: (Union[str, Instrument], float, SIDE, Optional[float], Optional[POSITION_EFFECT]) -> Optional[Order]
    """
    通用下单函数,策略可以通过该函数自由选择参数下单。

    :param id_or_ins: 下单标的物
    :param amount: 下单量,需为正数
    :param side: 多空方向
    :param price: 下单价格,默认为None,表示市价单
    :param position_effect: 开平方向,交易股票不需要该参数
    :example:
Esempio n. 23
0
@export_as_api
def symbol(order_book_id, split=", "):
    if isinstance(order_book_id, six.string_types):
        return "{}[{}]".format(order_book_id, instruments(order_book_id).symbol)
    else:
        s = split.join(symbol(item) for item in order_book_id)
        return s


def now_time_str(str_format="%H:%M:%S"):
    return Environment.get_instance().trading_dt.strftime(str_format)


@export_as_api
@apply_rules(verify_env().portfolio_exists(), verify_that("quantity").is_number())
def order(order_book_id, quantity, price=None, style=None):
    """
    全品种通用智能调仓函数

    如果不指定 price, 则相当于下 MarketOrder

    如果 order_book_id 是股票,等同于调用 order_shares

    如果 order_book_id 是期货,则进行智能下单:

        *   quantity 表示调仓量
        *   如果 quantity 为正数,则先平 Sell 方向仓位,再开 Buy 方向仓位
        *   如果 quantity 为负数,则先平 Buy 反向仓位,再开 Sell 方向仓位

    :param order_book_id: 下单标的物
Esempio n. 24
0
from rqalpha.const import POSITION_DIRECTION
from rqalpha.environment import Environment

__all__ = []


def export_as_api(func):
    __all__.append(func.__name__)
    return decorate_api_exc(func)


@export_as_api
def get_positions():
    portfolio = Environment.get_instance().portfolio
    return reduce(add, (reduce(add, (p.positions
                                     for p in itervalues(a.positions)), [])
                        for a in itervalues(portfolio.accounts)), [])


@export_as_api
@apply_rules(
    verify_that("direction").is_in(
        [POSITION_DIRECTION.LONG, POSITION_DIRECTION.SHORT]))
def get_position(order_book_id, direction):
    position_proxy = Environment.get_instance(
    ).portfolio.positions[order_book_id]
    if direction == POSITION_DIRECTION.LONG:
        return position_proxy.long
    else:
        return position_proxy.short
Esempio n. 25
0
                                EXECUTION_PHASE.ON_BAR,
                                EXECUTION_PHASE.ON_TICK,
                                EXECUTION_PHASE.AFTER_TRADING,
                                EXECUTION_PHASE.SCHEDULED)
def get_open_orders():
    """
    获取当日未成交订单数据

    :return: List[:class:`~Order` object]
    """
    return Environment.get_instance().broker.get_open_orders()


@export_as_api
@apply_rules(
    verify_that("id_or_ins").is_valid_instrument(),
    verify_that("amount").is_number().is_greater_than(0),
    verify_that("side").is_in([SIDE.BUY, SIDE.SELL])
)
def submit_order(id_or_ins, amount, side, price=None, position_effect=None):
    """
    通用下单函数,策略可以通过该函数自由选择参数下单。

    :param id_or_ins: 下单标的物
    :type id_or_ins: :class:`~Instrument` object | `str`

    :param float amount: 下单量,需为正数

    :param side: 多空方向,多(SIDE.BUY)或空(SIDE.SELL)
    :type side: :class:`~SIDE` enum
Esempio n. 26
0

def to_date(date):
    if isinstance(date, datetime.datetime):
        return date.date()
    if isinstance(date, datetime.date):
        return date

    if isinstance(date, str):
        return parse(date).date()

    raise RQInvalidArgument('unknown date value: {}'.format(date))


@export_as_api
@apply_rules(verify_that('start_date').is_valid_date())
def get_split(order_book_ids, start_date=None):
    # type: (Union[str, List[str]], Optional[Union[str, datetime.date]]) -> pd.DataFrame
    """
    获取某只股票到策略当前日期前一天的拆分情况(包含起止日期)。

    :param order_book_ids: 证券代码,证券的独特的标识符,例如:'000001.XSHE'
    :param start_date: 开始日期,用户必须指定,需要早于策略当前日期

    :return: 查询时间段内的某个股票的拆分数据

        *   ex_dividend_date: 除权除息日,该天股票的价格会因为拆分而进行调整
        *   book_closure_date: 股权登记日
        *   split_coefficient_from: 拆分因子(拆分前)
        *   split_coefficient_to: 拆分因子(拆分后)
Esempio n. 27
0
def symbol(order_book_id, split=", "):
    if isinstance(order_book_id, six.string_types):
        return "{}[{}]".format(order_book_id,
                               instruments(order_book_id).symbol)
    else:
        s = split.join(symbol(item) for item in order_book_id)
        return s


def now_time_str(str_format="%H:%M:%S"):
    return Environment.get_instance().trading_dt.strftime(str_format)


@export_as_api
@apply_rules(verify_env().portfolio_exists(),
             verify_that("quantity").is_number())
def order(order_book_id, quantity, price=None, style=None):
    """
    全品种通用智能调仓函数

    如果不指定 price, 则相当于下 MarketOrder

    如果 order_book_id 是股票,等同于调用 order_shares

    如果 order_book_id 是期货,则进行智能下单:

        *   quantity 表示调仓量
        *   如果 quantity 为正数,则先平 Sell 方向仓位,再开 Buy 方向仓位
        *   如果 quantity 为负数,则先平 Buy 反向仓位,再开 Sell 方向仓位

    :param order_book_id: 下单标的物