不同时间框架下4小时RSI的EMA值不一致问题排查
问题描述
我尝试在不同时间框架下获取4小时周期RSI的EMA值,但发现4小时框架和日线框架下返回的数据不一致,不过该脚本在日内时间框架下运行正常。
原Pine Script代码
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © jeckwilke // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © jeckwilke //@version=5 indicator("My script") rsi = request.security(syminfo.tickerid, str.tostring("240"), ta.rsi(close,14), lookahead = barmerge.lookahead_on) rsiMa = request.security(syminfo.tickerid, "240", ta.ema(rsi, 7)) plot(rsiMa[1]) plot(rsiMa[2], color = color.purple)
问题原因
原代码中,计算rsiMa时,ta.ema(rsi,7)里的rsi是当前图表时间框架下拉取的4小时RSI数据,EMA计算是在当前框架而非4小时框架内执行的。切换到日线框架时,EMA的计算周期和逻辑与4小时框架内直接计算的结果不符,导致数据不一致。
修正后的代码
要确保所有计算都在4小时框架内完成,修改如下:
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © jeckwilke //@version=5 indicator("My script") // 在4小时框架内完成RSI及其EMA的计算 rsiMa = request.security(syminfo.tickerid, "240", ta.ema(ta.rsi(close, 14), 7), lookahead = barmerge.lookahead_on) plot(rsiMa[1]) plot(rsiMa[2], color = color.purple)
也可以拆分步骤,同样保证EMA在4小时框架内计算:
//@version=5 indicator("My script") // 拉取4小时框架下的RSI值 rsi_4h = request.security(syminfo.tickerid, "240", ta.rsi(close, 14), lookahead = barmerge.lookahead_on) // 拉取4小时框架下基于该RSI计算的EMA值 rsiMa = request.security(syminfo.tickerid, "240", ta.ema(rsi_4h, 7), lookahead = barmerge.lookahead_on) plot(rsiMa[1]) plot(rsiMa[2], color = color.purple)
说明
修改后,RSI和EMA的计算逻辑完全在4小时时间框架内执行,无论当前图表是4小时、日线还是其他周期,拉取的都是4小时框架下预计算好的结果,不同时间框架下的数据会保持一致。
内容的提问来源于stack exchange,提问作者Eduardo Moreira
相关产品推荐
相关产品推荐

