PineScript策略问题:仅单仓位达5%盈利时平仓而非全平
问题分析与修正方案
你的核心问题出在统一的entry ID和基于持仓平均价的止盈计算,导致金字塔开仓的所有仓位被同时平仓:
错误点拆解
- 共用Entry ID:所有开仓都使用
id="CALL",strategy.exit指定from_entry="CALL"时,会将该ID下的所有持仓全部平仓,而非单个仓位。 - 错误的止盈价格计算:
strategy.position_avg_price是当前所有持仓的平均成本,不是单个仓位的开仓价,导致止盈条件是整体持仓盈利达标,而非单个仓位。
修正后的代码
strategy(title="5% 单仓止盈测试", overlay=true, pyramiding=10) // 回测时间设置 testStartYear = input(2022, "回测起始年份") testStartMonth = input(8, "回测起始月份") testStartDay = input(1, "回测起始日期") testPeriodStart = timestamp(testStartYear, testStartMonth, testStartDay, 0, 0) testStopYear = input(2030, "回测结束年份") testStopMonth = input(12, "回测结束月份") testStopDay = input(30, "回测结束日期") testPeriodStop = timestamp(testStopYear, testStopMonth, testStopDay, 0, 0) // 回测时段背景色 testPeriodBackground = input(title="显示回测背景色?", type=input.bool, defval=true) testPeriodBackgroundColor = testPeriodBackground and time >= testPeriodStart and time <= testPeriodStop ? #6c6f6c : na bgcolor(testPeriodBackgroundColor, transp=97) // 参数设置 smaLength = input(title="SMA周期", type=input.integer, defval=17) stdLength = input(title="标准差周期", type=input.integer, defval=20) ubOffset = input(title="上轨偏移", type=input.float, defval=2.0, step=0.5) lbOffset = input(title="下轨偏移", type=input.float, defval=2.0, step=0.5) long_tp_inp = input(5, title='多头止盈比例(%)', step=0.1)/100 // 改为需求的5% testPeriod() => time >= testPeriodStart and time <= testPeriodStop // 指标计算 smaValue = sma(close, smaLength) stdDev = stdev(close, stdLength) upperBand = smaValue + stdDev * ubOffset lowerBand = smaValue - stdDev * lbOffset // 开仓条件 longCondition = crossover(close, lowerBand) // 为每个开仓生成唯一ID,用计数器区分 var int entryCounter = 0 if (longCondition and testPeriod()) entryCounter += 1 entryId = str.tostring(entryCounter) + "_CALL" strategy.entry(id=entryId, long=true) // 针对当前开仓设置独立止盈,用开仓价计算5%盈利目标 strategy.exit(id="EXIT_" + entryId, limit=close*(1+long_tp_inp), from_entry=entryId) // 绘图 plot(series=smaValue, title="SMA", color=color.blue) plot(series=upperBand, title="上轨", color=color.green, linewidth=2) plot(series=lowerBand, title="下轨", color=color.blue, linewidth=2)
关键修改说明
- 唯一Entry ID:用计数器
entryCounter生成每个开仓的独立ID(如1_CALL、2_CALL),确保每个仓位是独立的交易单元。 - 单仓止盈计算:直接用当前开仓的
close价格计算止盈,而非持仓平均价,保证每个仓位以自身开仓价为基准计算5%盈利。 - 独立Exit设置:每个开仓对应专属的
strategy.exit,只平仓对应的单个仓位。
内容的提问来源于stack exchange,提问作者Val.Val
相关产品推荐
相关产品推荐

