如何为PineScript不同时间框架趋势线分配独立买卖颜色
解决不同时间框架趋势线的独立买卖颜色分配问题
需求:为两个不同时间框架的趋势线各分配一组独立的买卖颜色(共4种:趋势1买/卖、趋势2买/卖)。使用input.timeframe和自定义函数时,常规条件格式分配颜色的方法受限,多次尝试代码均未成功,寻求可行方案。
原尝试代码
//Code: res = input.timeframe(title='Trend 1', defval="") res2 = input.timeframe(title='Trend 2', defval="15") buyColor = color.green sellColor = color.red //buyColor2 for Trend2 //SellColor2 for Trend2 Function() => var int trend = 0 var float up = 0.0 var float down = 0.0 // lots of redacted calcs from custom function here for simplification htColor = trend == 0 ? buyColor : sellColor ht = trend == 0 ? up : down [ht, htColor] [ht2, htColor2] = request.security(syminfo.tickerid, res, Function()) [ht3, htColor3] = request.security(syminfo.tickerid, res2, Function()) plot(ht2, color=htColor2, title="Trend 1", linewidth=2) plot(ht3, color=htColor3, title="Trend 2", linewidth=2) //END OF CODE
更新后的尝试代码
// 更新尝试代码: timeFrame1 = "5" timeFrame2 = "15" res = input.timeframe(title='Trend 1', defval=timeFrame1) res2 = input.timeframe(title='Trend 2', defval=timeFrame2) trend1TF = str.tonumber(timeFrame1) trend2TF = str.tonumber(timeFrame2) buyColor = color(na) sellColor = color(na) if trend1TF == 5 buyColor := color.aqua else color(na) if trend2TF == 15 buyColor := color.blue else color(na) if trend1TF == 5 sellColor := color.orange else color(na) if trend2TF == 15 sellColor := color.red else color(na)
解决方案
问题核心在于自定义函数直接引用全局颜色变量,无法区分不同时间框架的颜色需求。正确做法是让自定义函数接受颜色参数,调用时为不同时间框架传入专属颜色。
修正后的完整代码
// 定义两组独立的买卖颜色 trend1BuyColor = color.aqua trend1SellColor = color.orange trend2BuyColor = color.blue trend2SellColor = color.red // 时间框架输入 res = input.timeframe(title='Trend 1', defval="5") res2 = input.timeframe(title='Trend 2', defval="15") // 修改自定义函数,添加颜色参数 getTrendData(buyCol, sellCol) => var int trend = 0 var float up = 0.0 var float down = 0.0 // 保留你的趋势计算逻辑(以下为示例,替换成你的实际代码) trend := close > open ? 0 : 1 up := ta.sma(close, 20) down := ta.sma(close, 50) htColor = trend == 0 ? buyCol : sellCol ht = trend == 0 ? up : down [ht, htColor] // 为不同时间框架传入对应的颜色参数 [ht2, htColor2] = request.security(syminfo.tickerid, res, getTrendData(trend1BuyColor, trend1SellColor)) [ht3, htColor3] = request.security(syminfo.tickerid, res2, getTrendData(trend2BuyColor, trend2SellColor)) // 绘制趋势线 plot(ht2, color=htColor2, title="Trend 1", linewidth=2) plot(ht3, color=htColor3, title="Trend 2", linewidth=2)
关键修改说明
- 把自定义函数改成带参数的形式,接受
buyCol和sellCol作为输入,让不同时间框架可以传入不同颜色 - 提前定义好两组独立的买卖颜色,避免全局变量冲突
- 调用
request.security时,分别为两个时间框架传入对应的颜色参数
这样就能实现两个趋势线各自使用独立的买卖颜色,解决之前的颜色分配问题。
内容的提问来源于stack exchange,提问作者PPP
相关产品推荐
相关产品推荐

