Pine Script v4 strategy.entry函数limit参数未按预期运行问题咨询
问题核心原因
你对strategy.entry的limit参数存在理解错误,这是你代码无法平仓的核心原因:strategy.entry的limit参数是入场限价,仅用于控制开仓的触发价格,不会自动生成平仓止盈订单。
你当前的代码逻辑是:满足开仓条件时,提交一个价格为long_take_profit(比当前收盘价高1%左右)的限价多单,相当于要求价格涨到这个高位才开多,开仓后没有配置任何平仓规则,自然仓位会一直持有无法平仓。
strategy.exit的from_entry参数失效原因
你用tostring(timenow)作为订单id的后缀,这个值精确到毫秒,每根K线、每个行情tick都会变化。你没有持久化存储每笔入场的订单id,后续执行exit逻辑时传入的from_entry id是最新的timenow生成的,和之前开仓的订单id完全对不上,自然会被忽略。
修复方案
第一步 先修复代码里的明显错误
你当前代码中直接使用了hist_security[1] > hist_security[2]的判断,但没有定义hist_security变量,运行时会直接报错,需要先补充定义或者删除这个判断条件。
第二步 实现每笔入场独立止盈的金字塔加仓逻辑
不要用timenow生成订单id,改用当前K线的time变量作为后缀,同根K线内这个值不会变化,开仓后立刻在同一个条件代码块内提交对应id的止盈单,就能保证每笔入场对应独立的止盈:
//@version=4 strategy(title="Cross Checks", pyramiding=5, shorttitle="CC", max_bars_back=200, default_qty_type=strategy.percent_of_equity, default_qty_value=5, initial_capital=100000, calc_on_every_tick=true, calc_on_order_fills=true, process_orders_on_close=true, commission_type=strategy.commission.percent, commission_value=0.00, slippage = 2, overlay=false) // Getting inputs window() => true fast_length = input(title="Fast Length", type=input.integer, defval=12) slow_length = input(title="Slow Length", type=input.integer, defval=26) src = input(title="Source", type=input.source, defval=close) // Calculating fast_ema = ema(src, fast_length) slow_ma = sma(src, slow_length) ema = ema(close, 100) rsi = rsi(close, 14) cci = cci(close, 14) spread = 0.0009 profit_perc = 0.0100 cross_long = crossover(fast_ema, slow_ma) check_ema_long = low > ema and ema > ema[1] check_rsi_long = rsi < 90 and rsi > 40 and rsi > rsi[1] check_cci_long = cci < 180 and cci > -50 and cci > cci[1] // 已删除未定义的hist_security相关判断,需要用请自行补充定义 cross_short = crossunder(fast_ema, slow_ma) check_ema_short = high < ema and ema < ema[1] check_rsi_short = rsi < 60 and rsi > 20 and rsi < rsi[1] check_cci_short = cci > -180 and cci < 50 and cci < cci[1] check_spread = spread < profit_perc condition_entry_long = cross_long and check_rsi_long and check_cci_long and check_ema_long and check_spread condition_entry_short = cross_short and check_rsi_short and check_cci_short and check_ema_short and check_spread // take profit strategy long_take_profit = close * (1 + profit_perc - spread) short_take_profit = close * (1 - profit_perc + spread) if condition_entry_long entry_id = "Long " + tostring(time) strategy.entry(entry_id, long=true, comment=tostring(long_take_profit, '#.##')) // 同代码块内直接提交对应id的止盈单,保证一一对应 strategy.exit("TP_" + entry_id, entry_id, limit=long_take_profit) if condition_entry_short entry_id = "Short " + tostring(time) strategy.entry(entry_id, long=false, comment=tostring(short_take_profit, '#.##')) strategy.exit("TP_" + entry_id, entry_id, limit=short_take_profit)
如果需要完全自己控制平仓逻辑,不用strategy.exit,也可以用var数组存储每笔入场的id、数量、止盈价,每次tick轮询数组判断价格是否触达止盈,调用strategy.close指定对应id平仓即可。
内容的提问来源于stack exchange,提问作者Nicola Trincas
相关产品推荐
相关产品推荐

