我正在尝试编写一个尾随值,该值仅在 ThinkScript 中满足条件时调整为新值

问题描述

类似于仅在出现新低或新高时才更改其值的预定义研究“PriceChannel”,我希望它仅在满足条件时更改其值,然后保持该值直到再次满足.

这是我到目前为止的代码,现在它检查最后一根柱线的“b”值,如果它 > 0,则绘制“b”,如果不是,则从最近的第二根柱线开始再次尝试,然后是第三个,依此类推,直到找到大于 0 的“b”值。

代码有效,但我必须为过去的每个第 n 个小节添加一个新的“else if”语句,300 个小节就足够了,但这意味着我必须输入同一行 300 次,然后每次只更改数字,我想避免这样做,另外,如果它检查 n=n+1 次,它会更干净。

对我应该做什么有什么建议吗?

plot b = if SMA30 crosses below 0 or
SZO crosses below 7 and SMA30 < SMA30[1]
then open
else 0;

plot g = if b>0
then b
else if b[1]>0
then b[1]
else if b[2]>0
then b[2]
else if b[3]>0
then b[3]
else 0;

解决方法

您可以使用递归变量。有两种方法可以做到这一点:

  • 简单的递归变量:
def gVal = if b > 0 then b else gVal[1];
plot g = gVal;
  • CompoundValue 递归变量:
def gVal = 
    CompoundValue(
      1,if GetValue(b,0) > 0 then GetValue(b,0) else GetValue(gVal,1),GetValue(b,0)
    );
plot g = gVal;

通常,递归变量可以正常工作。如果您的代码中有不同的“长度”或“偏移量”,则需要 CompoundValue(查看我的 answer here 以了解其工作原理)。


我用于测试的代码:

  • 正则递归变量
#hint: SO q: https://stackoverflow.com/q/66805478/1107226

def price_to_beat = 2.06;

declare lower;

# b could also be a plot; I had a separate plot,so I `def`d it here
def b =
    if open > price_to_beat
    then open
    else 0;

def gVal = if b > 0 then b else gVal[1];
plot g = gVal;

AddChartBubble(yes,gVal,"gVal:" + gVal,Color.YELLOW,no);

AddLabel(yes,"RecursiveVariable",Color.CYAN);

  • 复合价值
#hint: SO q: https://stackoverflow.com/q/66805478/1107226

def price_to_beat = 2.06;

declare lower;

# b could also be a plot; I had a separate plot,so I `def`d it here
def b = if open > price_to_beat
        then open
        else 0;

def gVal = 
    CompoundValue(
      1,0)
    );
plot g = gVal;
g.SetDefaultColor(Color.CYAN);

AddChartBubble(yes,g,"b: " + b + ",g: " + g,yes);

AddLabel(yes,"CompoundValue",Color.CYAN);

6 条形图上的测试结果图像:

6-Bar Chart showing results of test code for comparison

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...