3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 QMT 中,如果你计算出了一个自定义指标,想要将其画在 K 线图上进行观察,主要使用的是 ContextInfo.paint() 函数。
该函数需要在 handlebar(ContextInfo) 中调用,QMT 会逐根 K 线执行该函数,从而将指标数值连成线或画成柱状图。
ContextInfo.paint(name, value, index, line_style, color, limit)
0: 曲线(默认)42: 柱状线'noaxis': 不影响坐标轴缩放(即画在图上但不改变主图的纵坐标范围)。'nodraw': 不画线(仅显示数值)。下面是一个完整的策略代码示例。为了演示,我计算了一个简单的自定义指标:典型价格 (Typical Price),计算公式为 (最高价 + 最低价 + 收盘价) / 3,并将其画在图上。
# -*- coding: gbk -*-
def init(ContextInfo):
# 初始化函数,这里不需要做特殊设置
pass
def handlebar(ContextInfo):
# 1. 获取当前主图品种的代码
stock_code = ContextInfo.stockcode
# 2. 获取当前 K 线的数据(开高低收)
# count=1 表示只取最新的一根(当前正在运行的这根 K 线)
# 注意:get_market_data 返回的是 pandas DataFrame 或 Series
data = ContextInfo.get_market_data(
['high', 'low', 'close'],
stock_code=[stock_code],
count=1,
period=ContextInfo.period,
dividend_type=ContextInfo.dividend_type
)
# 3. 确保获取到了数据
if data.empty:
return
# 4. 提取数值 (由于返回的是结构化数据,我们需要提取出具体的 float 值)
# 注意:这里根据返回数据的结构,可能需要根据实际情况调整索引方式
# 在 handlebar 中单品种 count=1 通常返回 DataFrame,行索引为时间,列为字段
try:
current_high = data['high'].values[0]
current_low = data['low'].values[0]
current_close = data['close'].values[0]
except:
return # 数据异常则跳过
# 5. 计算自定义指标:典型价格 (Typical Price)
custom_indicator_value = (current_high + current_low + current_close) / 3
# 6. 将指标画在图上
# 参数说明:名称, 数值, 索引(-1), 线型(0为线), 颜色, 限制
ContextInfo.paint("典型价格", custom_indicator_value, -1, 0, "yellow")
# 示例:再画一条柱状图,例如显示收盘价,用红色柱状表示
# ContextInfo.paint("收盘柱状", current_close, -1, 42, "red")
ContextInfo.draw_text() 在特定位置写字,或使用 ContextInfo.draw_icon() 标记买卖点图标。paint 函数最后一个参数使用 'noaxis'。