3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在传统的 A 股市场交易规则中,实行的是 T+1 交易制度,即当日买入的股票需要等到下一个交易日才能卖出。然而,在进行某些高频交易、日内回转(T+0)策略研究、或者模拟可融券/日内对冲场景时,开发者往往需要在回测中实现买入后立即卖出的逻辑。
JoinQuant(聚宽)平台提供了实验性设置 API,允许开发者打破默认的规则限制,开启 T+0 交易模式。
在策略的 initialize(context) 初始化函数中,调用 set_option API 并设置 t0_mode 参数为 True 即可:
set_option("t0_mode", True)
除了 t0_mode 外,聚宽还提供了其他配套的实验性设置:
set_option("t0_mode", True) —— A股买入后可以立刻卖出。set_option("always_match_market_order", True) —— 支持在非交易时间下市价单,按照最新数据立即撮合。set_option("match_by_signal", True) —— 仅支持限价单,不对委托价格和成交数量检查而直接成交。以下示例演示了如何在 JoinQuant 中开启 T+0 模式,并在分钟级别回测中实现日内买入后随后的 Bar 立即卖出:
# 导入聚宽函数库
import jqdata
def initialize(context):
# 设定要操作的股票
g.security = '000001.XSHE'
# 设定基准
set_benchmark('000300.XSHG')
# 开启动态复权模式(真实价格)
set_option('use_real_price', True)
# 【关键设置】开启 T+0 模式,允许买入后当日卖出
set_option('t0_mode', True)
# 设置按分钟运行
run_daily(market_open, time='every_bar')
def market_open(context):
security = g.security
current_price = get_bars(security, count=1, unit='1m', fields=['close'])[0]['close']
# 获取当前可用资金与持仓情况
cash = context.portfolio.available_cash
position = context.portfolio.positions[security]
# 示例逻辑:早盘 09:35 买入 1000 股
if context.current_dt.hour == 9 and context.current_dt.minute == 35:
if cash > current_price * 1000:
order(security, 1000)
log.info("T+0模式:买入 %s 1000股" % security)
# 示例逻辑:早盘 10:00 卖出(在常规T+1下,当日买入此时间点无法卖出,但在T+0模式下可正常卖出)
elif context.current_dt.hour == 10 and context.current_dt.minute == 0:
if position.closeable_amount > 0 or position.total_amount > 0:
order_target(security, 0)
log.info("T+0模式:日内卖出 %s 所有持仓" % security)
t0_mode 属于平台的实验性功能,主要用于策略测试或特定交易逻辑模拟,请勿直接混淆真实的 A 股实盘交易规则。