Thinkscript 中的 If 语句

If statement in Thinkscript

我是一名初级 thinkscript 程序员,我学习 thinkscript 语法的速度非常快。但是,我在使用 if 语句时遇到了问题。我知道您可以在一个 if 块中有一个语句,但是可以在一个 if 块中有多个语句吗?

不是:if (condition) then (this) else (that);

但是:如果(条件)那么{(这个); (那个);};

有可能。只是将绘图变量误认为是条件语句,因为它们反过来使用条件语句绘制图形。

thinkScript 本质上具有三种形式的 if 用法。所有三种形式都需要一个 else 分支。一种形式允许设置或绘制一个或多个值。其他两个只允许设置或绘制一个值。

  1. if语句:可以设置一个或多个值,对于plotdef变量,括号内。
def val1;
plot val2;
if (cond) {
  val1 = <value>;
  val2 = <value>;
} else {
  # commonly used options:

  # sets the variable to be Not a Number
  val1 = Double.NaN;

  # sets the variable to what it was in the previous bar
  # commonly used for recursive counting or retaining a past value across bars
  val2 = val2[1];
}
  1. if 表达式:用于设置值的一体化表达式。 只能根据一个条件设置一个值,但可以在其他语句中使用。此版本通常用于跨栏递归计数项目并显示不同的颜色,例如,基于条件。
def val1 = if <condition> then <value if true> else <value if false>;
  1. if 功能:和上面的类似,但是更简洁,这是thinkScript(r)版本的三元条件语句。不同之处在于 truefalse 必须是双精度值 。因此,它不能用于设置颜色,或者其他不代表双精度值的项目。
def var1 = if(<condition>, <value if true>, <value if false>);

以下示例修改自 the thinkScript API doc for the if function,演示了如何使用所有三个版本。我添加了第二个变量来演示 if 语句如何根据相同条件一次设置多个值:

# using version 3, "if function"
plot Maximum1 = if(close > open, close, open);

# using version 2, "if expression"
plot Maximum2 = if close > open then close else open;

# using version 1, "if statement", with two variables, a `plot` and a `def`
plot Maximum3;
def MinimumThing;
if close > open {
    Maximum3 = close;
    MimimumThing = open;
} else {
    Maximum3 = open;
    MinimumThing = close;
}

作为旁注,虽然示例没有显示,但可以使用 def 关键字以及 plot 关键字来使用这些语句定义变量的值。