thinkScript 本质上具有if 的三种用法。所有三种形式都需要else 分支。一种形式允许设置或绘制一个或多个值。另外两个只允许设置或绘制一个值。
-
if 声明:可以设置一个或多个值,用于plot 或def 变量,在括号内。
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];
}
-
if 表达式:用于设置值的多合一表达式。 只能根据条件设置一个值,但可以在其他语句中使用。此版本通常用于对条形中的项目进行递归计数,以及根据条件显示不同的颜色。
def val1 = if <condition> then <value if true> else <value if false>;
-
if 函数:类似于上面的,但更紧凑,这是 thinkScript(r) 的三元条件语句版本。区别在于 true 和 false 值必须是双精度值。因此,它不能用于设置颜色等不代表双精度值的项目。
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 关键字来定义这些语句的变量值。