3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 JoinQuant(聚宽)量化交易平台中,若要进行高频交易或捕捉盘口瞬时微观结构变动,可以通过 get_current_tick 函数配合 Tick 级别的事件订阅实现实时盘口数据的获取与策略撮合。
get_current_tick 用于获取离指定时刻最近的一条 Tick 快照数据,包含了买卖五档(期货为一档)、最新价、成交量等盘口信息。
get_current_tick(security, dt=None, df=False)
'RB1909.XSGE'),不可使用主力合约(如 'RB9999.XSGE')。datetime 格式时刻,指定时返回离该时刻最近的 Tick。默认为 None(当前时刻)。False(返回 Tick 对象或字典)。注意:
get_current_tick依赖上下文,仅支持在回测与模拟交易的run_daily、handle_data或handle_tick中调用。
编写 Tick 策略时,需注意以下运行逻辑:
set_option('use_real_price', True)。subscribe(security, 'tick') 订阅具体合约的 Tick 事件。handle_tick(context, tick)。以下示例展示了如何在聚宽平台订阅螺纹钢期货合约(RB1909.XSGE),并在 handle_tick 回调中读取实时盘口数据进行交易决策:
# 导入聚宽数据库
import jqdata
def initialize(context):
# 设定真实价格模式(Tick策略必须设置)
set_option('use_real_price', True)
# 设置期货账户子仓位
init_cash = context.portfolio.starting_cash
set_subportfolios([SubPortfolioConfig(cash=init_cash, type='futures')])
# 保存目标期货合约(必须为具体合约)
g.security = 'RB1909.XSGE'
# 设定盘前与盘后定时任务
run_daily(before_market_open, time='08:30', reference_security='RB9999.XSGE')
run_daily(after_market_close, time='15:30', reference_security='RB9999.XSGE')
def before_market_open(context):
# 开盘前订阅 Tick 事件
subscribe(g.security, 'tick')
log.info("已订阅 %s 的 Tick 数据" % g.security)
def handle_tick(context, tick):
# 获取当前标的的最新 Tick 对象
current_tick = get_current_tick(g.security)
if current_tick is None:
return
# 读取盘口数据
latest_price = current_tick.current
ask_price_1 = current_tick.a1_p # 卖一价
bid_price_1 = current_tick.b1_p # 买一价
ask_volume_1 = current_tick.a1_v # 卖一量
bid_volume_1 = current_tick.b1_v # 买一量
# 打印盘口信息
log.info("最新价: %.2f | 买一: %.2f(量:%d) | 卖一: %.2f(量:%d)" %
(latest_price, bid_price_1, bid_volume_1, ask_price_1, ask_volume_1))
# 简单示例策略:如果买一量远大于卖一量,尝试开多仓
positions = context.portfolio.long_positions
if bid_volume_1 > ask_volume_1 * 3 and g.security not in positions:
order(g.security, 1, side='long')
log.info("买盘力量强劲,开多单 1 手")
def after_market_close(context):
# 收盘后取消订阅
unsubscribe_all()
log.info("已取消所有 Tick 订阅")
RB9999.XSGE 等主力/指数合约下单,需通过 get_dominant_future('RB') 动态获取当前映射的具体合约代号。handle_tick 中编写高耗时的耗时计算或复杂数据库查询,以免触发 1800 秒运行超时限制。