3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 ptrade 的 tick_data(context, data) 事件中,data 字典包含了高频的 Tick 级数据。若要统计主动买卖盘的即时成交差额,我们需要利用 data[security]['transcation'](逐笔成交数据)。
在逐笔成交(transcation)的 DataFrame 中,有两个关键字段:
business_direction(成交方向):
1 代表 买入(主动买盘 / 外盘:买方主动以卖出价成交,推动价格上涨)。0 代表 卖出(主动卖盘 / 内盘:卖方主动以买入价成交,推动价格下跌)。business_amount(成交量):该笔成交的股数。通过在 tick_data 触发时(默认每3秒一次),累加当前切片中 business_direction == 1 的成交量(主动买入量)与 business_direction == 0 的成交量(主动卖出量),即可计算出即时资金流向差额(Net Volume Flow)。
initialize 中开启 set_universe。transcation。business_direction == 1)和主动卖盘(business_direction == 0)。净主动买入量 = 主动买入总量 - 主动卖出总量。# -*- coding: utf-8 -*-
def initialize(context):
# 设置操作标的(以恒生电子为例)
g.security = '600570.SS'
set_universe(g.security)
# 策略自定义全局变量
g.threshold = 50000 # 触发交易的净主动买入量阈值(股)
g.buy_flag = False
def before_trading_start(context, data):
# 每日盘前重置状态
g.buy_flag = False
def tick_data(context, data):
security = g.security
if security not in data:
return
# 获取逐笔成交数据
transaction_df = data[security].get('transcation')
# 确保获取到了有效的逐笔成交数据(需要Level 2行情支持)
if transaction_df is None or transaction_df.empty:
return
# 1. 筛选主动买盘(外盘):business_direction 为 1
active_buy = transaction_df[transaction_df['business_direction'] == 1]
active_buy_vol = active_buy['business_amount'].sum()
# 2. 筛选主动卖盘(内盘):business_direction 为 0
active_sell = transaction_df[transaction_df['business_direction'] == 0]
active_sell_vol = active_sell['business_amount'].sum()
# 3. 计算即时成交差额
net_volume_flow = active_buy_vol - active_sell_vol
log.info(f"[{security}] 当前Tick - 主动买入: {active_buy_vol} 股, 主动卖出: {active_sell_vol} 股, 净流向: {net_volume_flow} 股")
# 获取当前持仓
pos = get_position(security)
# 4. 交易信号判断
if net_volume_flow > g.threshold and not g.buy_flag and pos.amount == 0:
# 主动买盘极度强势,以买一档价格买入1000股
order_tick(security, 1000, priceGear='1')
g.buy_flag = True
log.info(f"主动买盘强势,触发买入委托:1000股")
elif net_volume_flow < -g.threshold and pos.enable_amount > 0:
# 主动卖盘极度强势,平仓卖出所有可用持仓
order_tick(security, -pos.enable_amount, priceGear='-1')
g.buy_flag = False
log.info(f"主动卖盘强势,触发卖出平仓:{pos.enable_amount}股")
def handle_data(context, data):
# tick级别策略主要逻辑在tick_data中运行,handle_data保持pass即可
pass
transcation)及成交方向字段需要券商账户开通 Level 2 高级行情 权限,否则 data[security]['transcation'] 将返回 None。tick_data 中进行委托下单时,必须使用专用的 order_tick 接口,不能使用普通的 order 或 order_target 接口。priceGear(档位)以确保快速成交,同时注意控制交易成本。