Skip to content

约定函数

init - 策略初始化

python
init(context)

提供策略启动时的初始化上下文数据,在回测和实时模拟交易开始时触发一次。该回调接收 context 策略上下文对象。

参数

参数名类型说明
contextStrategyContext object策略上下文

范例

python
def init(context):
    # cash_limit的属性是根据用户需求自己定义的,你可以定义无限多种自己随后需要的属性,ricequant的系统默认只是会占用context.portfolio的关键字来调用策略的投资组合信息
    context.cash_limit = 5000

handle_bar - k 线数据更新

python
handle_bar(context, bar_dict)

提供 bar 数据更新时的策略上下文和当前合约池 bar 数据。bar_dict 中包含以 order_book_id 为键的 bar 对象数据,适用于日级别和分钟级别的 bar 更新场景。

参数

参数名类型说明
contextStrategyContext object策略上下文
bar_dictDict[BarObject]key 为 order_book_id,value 为 bar 对象

范例

python
def handle_bar(context, bar_dict):
    # put all your algorithm main logic here.
    # ...
    order_shares('000001.XSHE', 500)
    # ...

handle_tick - 快照数据更新

python
handle_tick(context, tick)

提供 tick 级别策略中的策略上下文和已订阅合约快照数据更新。支持多个合约分别触发,触发时间包括集合竞价和连续交易时段。

参数

参数名类型说明
contextStrategyContext object策略上下文
tickTickObject objectkey 为 order_book_id,value 为 bar 数据。当前合约池内所有合约的 bar 数据信息都会更新在 bar_dict 里面

范例

python
def handle_tick(context, tick):
    # put all your algorithm main logic here.
    # ...
    order_shares(tick.order_book_id, tick.last)
    # ...

open_auction - 集合竞价

python
open_auction(context, bar_dict)

提供盘前集合竞价阶段的策略上下文和合约池 bar 数据。bar_dict 中为不完整的 bar 对象,包含 openlimit_uplimit_down 等集合竞价阶段数据。

参数

参数名类型说明
contextStrategyContext object策略上下文
bar_dictDict[BarObject]key 为 order_book_id,value 为 不完整的 bar 对象,该对象仅有 open, limit_up, limit_down 等字段,没有 close 等字段

范例

python
def open_auction(context, bar_dict):
    # put all your algorithm main logic here.
    # ...
    order_book_id = "000001.XSHE"
    order_shares(order_book_id, bar_dict[order_book_id].open)
    # ...

before_trading - 盘前

python
before_trading(context)

提供每日开始交易前的策略上下文数据。触发时间取决于当前订阅合约的交易时间,例如存在夜盘交易的期货合约时,可能在前一日夜间触发。

举例来说,如果用户订阅的合约中存在有夜盘交易的期货合约,则该函数可能会在前一日的 20:00 触发,而不是早晨 08:00.

参数

参数名类型说明
contextStrategyContext object策略上下文

范例

python
def before_trading(context):
    logger.info("This is before trading")

after_trading - 盘后

python
after_trading(context)

提供每日收盘后的策略上下文数据。在实时模拟交易中,该回调会在每天 15:30 触发。

参数

参数名类型说明
contextStrategyContext object策略上下文

范例

python
def after_trading(context):
    # 可以进行收盘后的计算和日志记录
    pass