基于OHLC表规则生成bar_type列及多时间维度计算的DolphinDB求助
在DolphinDB中为多时间维度OHLC表添加bar_type列
核心思路
先明确规则优先级:规则3(同时突破前一根K线高低点)优先级最高,其次是规则2(突破高点或低点),最后是规则1(当前K线被前一根完全包含)。利用DolphinDB的prev()窗口函数获取前一根K线的high/low值,结合条件判断完成赋值;针对多时间维度,通过分组保证每个标的、每个周期内独立计算。
代码实现
假设你的OHLC表名为ohlc_data,包含字段:symbol(交易标的)、period(时间维度,如"5m"/"30m"/"1D"等)、timestamp(时间戳)、open/high/low/close。
1. 数据预处理(确保排序正确)
先按标的、时间维度、时间戳排序,保证前一行是对应周期的上一根K线:
ohlc_data = select * from ohlc_data order by symbol, period, timestamp
2. 添加bar_type列
通过嵌套条件判断实现规则逻辑,用context by指定分组维度:
ohlc_data = select *, iif(prev(high) < high and prev(low) > low, 3, iif(prev(high) < high or prev(low) > low, 2, iif(prev(high) >= high and prev(low) <= low, 1, NULL) ) ) as bar_type from ohlc_data context by symbol, period
代码说明
context by symbol, period:确保每个标的、每个时间维度下独立计算前一根K线的数据- 条件顺序:先判断规则3,再规则2,最后规则1,避免逻辑冲突
- 首行数据因无前驱K线,
bar_type为NULL,可根据需求手动赋值(如设为0)
多时间维度适配
将逻辑封装为函数,方便批量处理不同周期的OHLC数据:
def addBarType(ohlcTable){ ohlcTable = select * from ohlcTable order by symbol, period, timestamp return select *, iif(prev(high) < high and prev(low) > low, 3, iif(prev(high) < high or prev(low) > low, 2, iif(prev(high) >= high and prev(low) <= low, 1, NULL) ) ) as bar_type from ohlcTable context by symbol, period } // 调用示例 ohlc_with_bar_type = addBarType(ohlc_data)
结果验证
可抽取部分数据验证逻辑正确性:
select symbol, period, timestamp, prev(high) as prev_high, high, prev(low) as prev_low, low, bar_type from ohlc_with_bar_type where symbol = 'BTCUSDT' and period = '5m' limit 10
内容的提问来源于stack exchange,提问作者Huang WeiFeng
相关产品推荐
相关产品推荐

