3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 PTrade 平台交易上证科创板股票时,由于科创板股票设置了价格笼子(如上下 2% 的限制)及特殊的撮合机制,直接使用普通市价单可能面临不成交或滑点过大的风险。为了保障交易安全,科创板市价委托引入了**保护限价(limit_price)**机制。
在 PTrade 中,市价下单需使用 order_market 接口:
order_market(security, amount, market_type, limit_price=None)
str): 股票代码,如 '688001.SS'(科创板标的)。int): 委托数量。正数为买入,负数为卖出。int): 市价委托类型。上证科创板支持以下类型:
0: 对手方最优价格1: 最优五档即时成交剩余转限价2: 本方最优价格4: 最优五档即时成交剩余撤销float): 保护限价(仅限科创板股票)。保护限价是投资者在进行市价委托时预先设定的最高可接受买入价或最低可接受卖出价:
limit_price 为允许买入的价格上限。若市场撮合价格高于该值,超出的委托将被限制或撤销。limit_price 为允许卖出的价格下限。若市场撮合价格低于该值,超出的委托将被限制或撤销。注意:如果不传 limit_price 或设置不当,在行情剧烈波动时可能导致委托失败或产生严重滑点。
通常做法是基于当前盘口的最新价(last_px)、卖一价(offer_grp)或买一价(bid_grp),加上/扣除一定比例的缓冲浮动(如 2%)。
def initialize(context):
g.security = '688001.SS'
set_universe(g.security)
def handle_data(context, data):
security = g.security
# 获取当前行情快照
snapshot = get_snapshot(security)
if not snapshot or security not in snapshot:
return
last_price = snapshot[security]['last_px']
# 1. 买入场景:设置保护限价为当前最新价的 102%(允许最高 2% 滑点)
buy_limit_price = round(last_price * 1.02, 2)
# 使用“最优五档即时成交剩余转限价”(market_type=1) 买入 100 股
order_market(security, 100, market_type=1, limit_price=buy_limit_price)
log.info("买入委托已发送,保护上限: %s" % buy_limit_price)
# 2. 卖出场景:设置保护限价为当前最新价的 98%(允许最低 2% 滑点)
sell_limit_price = round(last_price * 0.98, 2)
# 使用“最优五档即时成交剩余撤销”(market_type=4) 卖出 100 股
# order_market(security, -100, market_type=4, limit_price=sell_limit_price)
round(price, 2) 进行精度处理,避免因小数精度超标导致柜台报单失败。get_snapshot 时务必增加判空保护,防止因行情未推送导致获取 last_px 报错。on_order_response 和 on_trade_response 实时捕获订单回报,确保市价单触发保护限价后的处理逻辑符合策略预期。