You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pine Script简易策略无法在图表显示,请求排查解决

问题分析与解决

一、脚本无效果的核心原因

你的策略完全没触发,是因为买卖条件的判断逻辑完全错误,和你想要的连续阴K开仓、收阳平仓逻辑完全不匹配:

1. 做多条件写崩了

你写的close < CandlesBack是把收盘价和输入的整数2直接比较,这根本不是判断连续2根阴K的逻辑。正确的判断应该是:当前K线的前两根K线都收阴(收盘价低于开盘价),同时当前无持仓、在设定的日期范围内。

修正后的做多条件:

buycondition = close[1] < open[1] and close[2] < open[2] and strategy.position_size == 0 and dateFilter

2. 平仓条件也错了

你写的CandlesForward > open是把输入的整数1和开盘价比较,这和“收阳平仓”的逻辑八竿子打不着。正确的平仓条件应该是:当前有持仓,且当前K线收阳(收盘价高于开盘价)。

修正后的平仓条件:

sellcondition = close > open and strategy.position_size > 0

3. 冗余变量没用上

你定义的CandlesBack和CandlesForward两个输入变量,在原始代码里完全没发挥作用——你本来是想用它们指定回溯/向前的K线数,但错误地把它们和价格直接比较了。如果逻辑固定是连续2根阴K开仓、收阳平仓,这俩变量可以直接删掉;如果想做成可配置(比如让用户选连续N根阴K开仓),可以调整判断逻辑,比如用ta.barssince实现:

CandlesBack = input.int(title="连续阴K数量", defval=2, step=1)
buycondition = ta.barssince(close >= open) >= CandlesBack and strategy.position_size == 0 and dateFilter

这个逻辑是判断距离最近的阳K已经过去了至少CandlesBack根K线,也就是连续CandlesBack根阴K。

二、代码缩进问题

不是所有行都要加4空格,只有代码块内的语句需要缩进:比如if、for这类控制结构下面的执行代码,必须相对于父语句缩进4个空格(或者按Tab键,Pine编辑器会自动处理)。你原始代码里if buycondition和下面的strategy.entry是同一层级,这会导致逻辑不生效甚至报错,正确的缩进应该是:

if buycondition
    strategy.entry(id="long", direction=strategy.long)
    buyPrice := open

平仓的if块也要同理缩进。

三、完整修正后的脚本

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © elasticc

//@version=5
strategy("s2",
    initial_capital=4000, 
    default_qty_type=strategy.percent_of_equity, 
    default_qty_value=100,
    overlay=true, 
    use_bar_magnifier=true)

// 日期过滤
i_time              = input.time(title="开始日期", defval=timestamp("01 Jan 2020"))
i_time2             = input.time(title="结束日期", defval=timestamp("01 Jan 2099"))
dateFilter          = time >= i_time and time <= i_time2

// 买卖条件判断
var float buyPrice  = 0
buycondition        = close[1] < open[1] and close[2] < open[2] and strategy.position_size == 0 and dateFilter          
sellcondition       = close > open and strategy.position_size > 0 

// 开仓
if buycondition
    strategy.entry(id="long", direction=strategy.long)
    buyPrice := open

// 平仓
if sellcondition
    strategy.close(id="long", comment="Exit")
    buyPrice := na

// 绘制开仓价格线
plot(buyPrice, color=color.green, style=plot.style_linebr)

内容的提问来源于stack exchange,提问作者candlestickb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 09:45:50