为何Pine Script带limit限价的市价单仍在下一根K线开盘价入场
问题排查与修复
以下是代码中导致限价单未按预期触发的核心问题,以及对应修复方案:
1. 入场条件逻辑错误
你将low < entry_price和entry_condition放在strategy.entry的when参数中同时判断,等于在RSI信号触发的同一根K线就校验价格是否满足条件,违背了「下一根K线挂限价单」的逻辑。Pine Script策略默认当前K线收盘后才确认信号有效性,不需要主动判断价格是否触及限价,系统会自动在后续K线中校验挂单价是否被触发。
2. 平仓10根K线的判断逻辑错误
当前用entry_condition[10]判断入场满10根K线,这个判断是基于信号触发时间,而非实际成交时间,会出现信号触发但未成交就提前平仓的错误,应该用持仓的入场K线索引来计算持仓时间。
3. 策略参数与需求不匹配
需求是2周期RSI下穿10买入、上穿90卖出,但原代码的买入RSI默认值为5、卖出默认值为40,需要调整参数默认值。
完整修正代码
//@version=4 strategy("2RSI Strategy by Larry Connor", overlay=true) rsi_length = input(title="RSI Length", defval=2) buying_rsi_value = input(title="Buy at RSI Value", defval=10) selling_rsi_value = input(title="Sell at RSI Value", defval=90) price = close rsi = rsi(price, rsi_length) buy = crossunder(rsi, buying_rsi_value) sell = crossover(rsi, selling_rsi_value) date = tostring(dayofmonth) + '-' + tostring(month) + '-' + tostring(year) disable_date_ranges = input(title="Disable Date Ranges", defval=true) start_date = input(title="Start Date", type=input.time, defval=timestamp("19 Oct 2020 00:00 +0530")) end_date = input(title="End Date", type=input.time, defval=timestamp("18 Oct 2021 00:00 +0530")) in_date_range = time >= start_date and time < end_date ema_len = input(200, minval=1, title="EMA Length") ema_src = input(close, title="EMA Source") ema_200 = ema(ema_src, ema_len) entry_condition= buy and ema_200 < price // 修正持仓10K平仓逻辑 pos_open_bar = strategy.opentrades.entry_bar_index(0) hold_10_bar = bar_index - pos_open_bar >= 10 exit_condition = sell or (strategy.opentrades > 0 and hold_10_bar) previous_day_close = close[1] two_percent_of_prev_day_close = previous_day_close * 0.02 entry_price = previous_day_close - two_percent_of_prev_day_close capital_invested = input(title="Invested capital", defval=100000) initial_capital = strategy.initial_capital capital_to_be_invested = capital_invested if(na(capital_invested) or capital_invested == 0) capital_to_be_invested = initial_capital // 修正入场条件,移除多余的low判断 if (not na(rsi) and (in_date_range or disable_date_ranges)) strategy.entry("buy", when=entry_condition, limit=entry_price, long= true, qty = capital_to_be_invested/entry_price, comment="Long") if (exit_condition) strategy.close("buy", true)
内容的提问来源于stack exchange,提问作者Abhishek
相关产品推荐
相关产品推荐

