打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
FMZ PINE Script 文档

关键字、语法、设置简介

代码结构

Pine中代码遵循的一般结构:

<version>
<declaration_statement>
<code>

注释

FMZ的Pine语言支持的注释符号:单行注释//、多行注释/* */,例如以下例子中的注释写法:

[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)  // 计算MACD指标

/*
plot函数在图表上画出指标线
*/
plot(macdLine, color = color.blue, title='macdLine')
plot(signalLine, color = color.orange, title='signalLine')
plot(histLine, color = color.red, title='histLine')

版本

以下形式的编译器指令告诉编译器该脚本是用哪个版本的Pine编写的:

//@version=5

默认为v5版本,代码中可以省略//@version=5

声明语句

  • indicator()
  • strategy()

声明语句确定脚本的类型,这又决定了其中允许哪些内容,以及如何使用和执行。设置脚本的关键属性,比如它的名称,当它被添加到图表中时,它将出现在哪里,它所显示的数值的精度和格式,以及管理其运行时行为的某些数值,比如它将在图表中显示的最大绘图对象数量。对于策略,属性包括控制回测的参数,如初始资本、佣金、滑点等。FMZ的Pine不要求一个策略代码中必须包含indicator()或者strategy()声明语句。

代码

脚本中不是注释或编译器指令的行是语句,它实现了脚本的算法。一个语句可以是这些内容之一。

  • 变量声明
  • 变量的重新赋值
  • 函数声明
  • 内置函数调用,用户定义的函数调用
  • ifforwhileswitch等结构

语句可以以多种方式排列

  • 有些语句可以用一行来表达,比如大多数变量声明、只包含一个函数调用的行或单行函数声明。其他的,像结构,总是需要多行,因为它们需要一个局部的块。
  • 脚本的全局范围内的语句(即不属于局部块的部分)不能以空格制表符(tab键)开始。它们的第一个字符也必须是该行的第一个字符。在行的第一个位置开始的行,根据定义成为脚本的全局范围的一部分。
  • 结构或多行函数声明总是需要一个local block。一个本地块必须缩进一个制表符或四个空格(否则,会被解析为上一行的串联代码,即被判定为上一行代码的连续内容),每个局部块定义了一个不同的局部范围。
  • 多个单行语句可以通过使用逗号(,)作为分隔符在一行中串联起来。
  • 一行中可以包含注释,也可以只是注释。
  • 行也可以被包起来(在多行上继续)。

例如,包括三个局部块,一个在自定义函数声明中,两个在变量声明中使用if结构,如下代码:

indicator("", "", true)             // 声明语句(全局范围),可以省略不写

barIsUp() =>                        // 函数声明(全局范围)
    close > open                    // 本地块(本地范围)

plotColor = if barIsUp()            // 变量声明 (全局范围)
    color.green                     // 本地块 (本地范围)
else
    color.red                       // 本地块 (本地范围)

runtime.log("color", color = plotColor)  // 调用一个内置函数输出日志 (全局范围)

换行代码

长行可以被分割在多行上,或被 "包裹 "起来。被包裹的行必须缩进任何数量的空格,只要它不是4的倍数(这些边界用于缩进局部块)。

a = open + high + low + close

可以被包装成(注意每行缩进的空格数量都不是4的倍数):

a = open +
      high +
          low +
             close

一个长的plot()调用可以被包装成。

close1 = request.security(syminfo.tickerid, "D", close)      // syminfo.tickerid 当前交易对的日线级别收盘价数据系列
close2 = request.security(syminfo.tickerid, "240", close)    // syminfo.tickerid 当前交易对的240分钟级别收盘价数据系列
plot(ta.correlation(close, open, 100),                       // 一行长的plot()调用可以被包装
   color = color.new(color.purple, 40),
   style = plot.style_area,
   trackprice = true)

用户定义的函数声明中的语句也可以被包装。但是,由于局部块在语法上必须以缩进开始(4个空格或1个制表符),当把它分割到下一行时,语句的延续部分必须以一个以上的缩进开始(不等于4个空格的倍数)。比如说:

test(c, o) =>
    ret = c > o ?
       (c > o+5000 ? 
          1 :
              0):
       (c < o-5000 ? 
          -1 : 
              0)

a = test(close, open)
plot(a, title="a")

时间序列

时间序列并不是一种数据类型或者格式,时间序列是PINE语言中一种基本结构的概念。用来储存时间上连续变动的值,每个值都对应一个时间点。时间序列这种概念的结构很适合应用于处理、记录随时间变化的一系列数据。
以内置变量open为例,open内置变量记录了每一根K线BAR的开盘价,如果这个open是5分钟K线周期的数据。那么这个open变量中记录的就是每个5分钟K线BAR(柱)的开盘价。当你的策略程序在执行时,代码中引用open即引用了当前所在K线BAR的开盘价。为了引用时间序列中之前的值(过去的值),我们使用[]历史操作符,当策略在某个K线BAR上执行时,open[1]的意思就是引用当前K线BAR的前一根K线BAR的开盘价。

虽然时间序列很容易让人想起「数组」这种数据结构,虽然PINE语言也有数组类型。但是它们和时间序列是完全不同的概念。

PINE语言这样设计时间序列,可以在策略代码中很轻松地计算收盘价的累计值,而且不需要使用for之类的循环结构,只用使用PINE语言的内置函数ta.cum(close)。再举个例子,我们需要计算最后14个K线BAR(即距离代码执行时的当前时刻最近的14根K线BAR)的最高价与最低价差值的平均值可以写为:ta.sma(high - low, 14)

在时间序列上调用函数的结果也会在时间序列上留下痕迹,同样可以使用[]历史操作符引用之前的值。例如,测试当前的K线BAR的收盘价是否超过最后10根K线BAR中的最高价的最大值时(不包括当前的K线BAR)。我们可以写为breach = close > ta.highest(close, 10)[1],同样也可以写成breach = close > ta.highest(close[1], 10)。所以ta.highest(close, 10)[1]ta.highest(close[1], 10)是等价的。

可以用以下代码验证:

strategy("test pine", "test", true) 

a = ta.highest(close, 10)[1]
b = ta.highest(close[1], 10)

plotchar(true, title="a", char=str.tostring(a), location=location.abovebar, color=color.red)
plotchar(true, title="b", char=str.tostring(b), location=location.belowbar, color=color.green)

以上测试代码会将a和b在每个BAR上输出其对应的时间序列上的值,可以看到a和b值一直都是相等的,所以这两种表示方法等价。

Pine语言交易类库模版参数

PINE策略的内置模板「Pine语言交易类库」的参数设置说明。

交易设置

  • 执行方式
    收盘价模型:当前BAR走完才执行模型,在下根BAR开始的时候执行交易。
    实时价模型:每次价格变动都执行模型,有信号立即执行交易。
  • 默认开仓手数:如果交易指令不指定交易数量时,按照该设置的数量执行交易。
  • 最大单次交易下单量:根据实际盘口,结合该参数设置,确定每次下单最大的数量,避免冲击盘面。
  • 滑价点数:根据定价货币精度参数和该参数确定下单时的滑价。例如,定价货币精度设置2,即精确到小数点第二位,精确到0.01。那么滑价点数每一点代表0.01个定价单位。此时滑价点数设置5,下单时的滑价就是0.05(滑价指下单时为了更好和盘口订单成交溢出的价格部分)。
  • 变量最长周期数:影响图表K线BAR数量,与javascript策略中调用SetMaxBarLen函数作用相同。

期货选项

  • 品种代码:合约代码,交易所对象为非现货交易所对象时才需要设置。
  • 最小合约张数:下单时,合约的最小交易量。

实盘选项

  • 自动恢复进度:自动恢复上次策略停止前的状态。
  • 下单重试次数:订单没有成交会撤销订单,重新下单尝试交易,该参数用来限定最大的重试次数。
  • 网络轮询间隔(毫秒):只对REST协议有效,控制网络请求间隔,避免请求过于频繁,超出交易所限制。
  • 账户同步时间(秒):同步账户数据的时间周期。
  • 开仓后仓位同步时间(毫秒):只针对一些交易所数据延迟导致的重复开仓,同步时间设置大一些可以缓解此类问题。
  • 杠杆倍数:设置杠杆倍数。

现货交易、其它设置

  • 一手交易量:默认一手的交易量,只针对现货有效。
  • 最小交易量:最小交易量。
  • 定价货币精度:价格精度,即价格的小数位数。
  • 交易品种精度:下单量精度,即下单量的小数位数。
  • 手续费:根据该设置对一些数据进行计算,0.002指千分之2。
  • 盈亏统计间隔:仅在实盘显示盈亏统计使用。
  • 失败重试(毫秒):网络请求失败时重试间隔。
  • 使用代理:只针对REST协议有效。
  • 隐藏常见网络错误:在日志区域隐藏常见错误日志。
  • 切换基地址:只针对REST协议有效。
  • 推送通知:推送消息到邮箱等。

下单交易

开仓

strategy(title = "open long example", pyramiding = 3)                                // pyramiding 允许的同方向下单的次数
strategy.entry("long1", strategy.long, 0.01)                                         // 市价开多仓,指定分组标签为long1
strategy.entry("long2", strategy.long, 0.02, when = close > ta.ema(close, 10))       // 条件触发,执行下单,市价开多仓
strategy.entry("long3", strategy.long, 0.03, limit = 30000)                          // 指定(较低的)价格,计划下买单订单,等待成交开仓,限价开仓

平仓

strategy(title = "close long example", pyramiding = 2)                              // pyramiding 允许的同方向下单的次数
strategy.entry("long1", strategy.long, 0.1)                                         // 市价开多仓,指定分组标签为long1
strategy.entry("long2", strategy.long, 0.1)                                         // 市价开多仓,指定分组标签为long2
strategy.close("long1", when = strategy.position_size > 0.1, qty_percent = 50, comment = "close buy entry for 50%")   // 平仓,指定平掉分组标签为long1的仓位的50%持仓
strategy.close("long2", when = strategy.position_size > 0.1, qty_percent = 80, comment = "close buy entry for 80%")   // 平仓,指定平掉分组标签为long2的仓位的80%持仓

交易机制

PINE语言的持仓机制类似于单向持仓。举例子,当持有多头方向的头寸时(多头持仓),如果有卖出操作的订单、计划单等(相对于持仓方向反方向的)订单触发执行,此时会先平掉多头方向的头寸(平掉所有多头持仓),然后再执行触发的(相对于平仓前持仓方向反方向的)订单。

计划单

使用下单指令下单时,如果不指定任何价格,默认为市价单。除了市价单还可以通过计划单下单,计划单并不会立即操作下单。计划单在没有触发时存在程序的计划委托队列中,可以在实盘/回测时状态信息(即策略运行时的状态栏)的「计划订单」表格分页中看到。当市场实时价格满足条件触发这些计划单时系统才会真正下单。所以这些订单在成交价格上存在略微偏差属于正常情况。使用strategy.entry函数下单时,我们可以指定limitstop参数。

var isTrade = false 
if not barstate.ishistory and not isTrade
    isTrade := true 
    strategy.entry("test 1", strategy.long, 0.1, stop=close*1.3, comment="test 1 order")                     // stop
    strategy.entry("test 2", strategy.long, 0.2, limit=close*0.7, comment="test 2 order")                    // limit
    strategy.entry("test 3", strategy.short, 0.3, stop=close*0.6, limit=close*1.4, comment="test 3 order")   // stop-limit    
  • limit 订单

    设置订单的限价,当订单为买单时(即direction参数为strategy.long),只有市场当前价格低于该价格时,订单才会触发。
    当订单为卖单时(即direction参数为strategy.short),只有市场当前价格高于该价格时,订单才会触发。

  • stop 订单

    设置订单的止损价,当订单为买单时,只有市场当前价格高于该价格时,订单才会触发。
    当订单为卖单时,只有市场当前价格低于该价格时,订单才会触发。

  • stop-limit 订单

    可以同时设置limitstop参数,订单在首先符合条件的价格触发。

声明、逻辑结构关键字

var

var 是用于分配和一次性初始化变量的关键字。
通常,不包含关键字var的变量赋值语法会导致每次更新数据时都会覆盖变量的值。 与此相反,当使用关键字var分配变量时,尽管数据更新,它们仍可以“保持状态”,只有在满足if-expressions中的条件时才更改它。

var variable_name = expression

说明:

  • variable_name - Pine Script中允许的用户变量的任何名称(可以包含大写和小写的拉丁字符,数字和下划线(_),但不能以数字开头)。
  • expression - 任何算术表达式,就像定义常规变量一样。 将计算表达式并将其分配给变量一次。

例子

// Var keyword example
var a = close
var b = 0.0
var c = 0.0
var green_bars_count = 0
if close > open
    var x = close
    b := x
    green_bars_count := green_bars_count + 1
    if green_bars_count >= 10
        var y = close
        c := y
plot(a, title = "a")
plot(b, title = "b")
plot(c, title = "c")

变量'a'保持系列中每个柱线的第一根柱线的收盘价。
变量'b'保持系列中第一个“绿色”价格棒的收盘价。
变量'c'保持系列中第十个“绿色”条的收盘价。

在FMZ上,分为实时价模型、收盘价模型,对于varvarip声明的变量我们使用以下代码测试。

strategy("test pine", "test 1", true) 

// 测试 var varip
var i = 0
varip ii = 0

// 将策略逻辑每轮改变的i、ii打印在图上
plotchar(true, title="ii", char=str.tostring(ii), location=location.abovebar, color=color.red)
plotchar(true, title="i", char=str.tostring(i), location=location.belowbar, color=color.green)

// 每轮逻辑执行都给i、ii递增1
if true
    i := i + 1
    ii := ii + 1
  • 实时价模型
    以上测试代码在执行时分为两个阶段:1、历史K线阶段。2、实时K线阶段。当在实时价模型、历史K线阶段时,varvarip声明的变量i、ii在策略代码每轮执行时都会执行递增操作(因为if true所以肯定执行对应的条件代码块)。所以可以看到回测结果K线BAR上显示的数字逐个都是递增1的。当历史K线阶段结束,开始实时K线阶段。varvarip声明的变量则开始发生不同的变化。因为是实时价模型,在一根K线BAR内每次价格变动都会执行一遍策略代码,i := i + 1ii := ii + 1都会执行一次。区别是ii每次都修改。i虽然每次也修改,但是下一轮执行策略逻辑时会恢复之前的值,直到当前K线BAR走完才更新确定i的值(即下一轮执行策略逻辑时不再恢复之前的值)。所以可以看到变量i依然是每根BAR增加1。但是变量ii每根BAR就累加了好几次。

  • 收盘价模型
    由于收盘价模型是每根K线BAR走完时才执行一次策略逻辑。所以在收盘价模型时,历史K线阶段和实时K线阶段,varvarip声明的变量在以上例子中递增表现完全一致,都是每根K线BAR递增1。

varip

varip(var intrabar persist)是用于分配和一次性初始化变量的关键词。它与var关键词相似,但是使用varip声明的变量在实时K线更新之间保留其值。

varip variable_name = expression

说明:

  • variable_name - Pine脚本中允许的用户变量的任何名称(可以包含大写和小写拉丁字符、数字和下划线(_),但不能以数字开头)。
  • expression - 任何算术表达式,就像定义常规变量时一样。在第一根K线上,表达式仅计算一次并将其分配给变量一次。

例子

// varip
varip int v = -1
v := v + 1
plot(v)

使用var时,绘图将返回bar_index的值。使用varip,在历史K线上会发生相同的行为,但是在实时K线上,该图将返回一个值,该值对于每一tick都增加一。

备注
只能与简单类型,例如float、int、bool、string,和这些类型的阵列一起使用。

true

表示一个布尔类型变量的值,或者当表达式使用比较逻辑运算符时可以计算的值。

备注
请参阅比较运算符和逻辑运算符的描述。

另见
bool

false

表示一个布尔类型变量的值,以及比较操作、逻辑操作的结果。

备注
请参阅比较运算符和逻辑运算符的描述。

另见
bool

if

If语句定义了在满足表达式条件时必须执行的语句块。第4版的Pine脚本语言允许您使用“else if”语法。

通用编码来自:

var_declarationX = if condition
    var_decl_then0
    var_decl_then1
    ...
    var_decl_thenN
    return_expression_then
else if [optional block]
    var_decl_else0
    var_decl_else1
    ...
    var_decl_elseN
    return_expression_else
else
    var_decl_else0
    var_decl_else1
    ...
    var_decl_elseN
    return_expression_else

备注
var_declarationX - 此变量获取if语句的值
condition - 如果条件为true,则使用语句块then中的逻辑(var_decl_then0var_decl_then1等)。如果条件为false,则使用语句块else if或者else中的逻辑(var_decl_else0var_decl_else1等)。
return_expression_then , return_expression_else - 模块中的最后一个表达式或者来自块else的表达式将返回语句的最终值。 如果变量的声明在最后,它的值将是结果值。

if语句的返回值的类型取决于return_expression_thenreturn_expression_else类型。TradingView上运行时,它们的类型必须匹配:当你在else块中有一个字符串值时,不可能从then语句块返回一个整数值。在FMZ上运行时,以下例子不会报错,当y值取值"open"时,plot画图时的数值为n/a。

例子

// This code compiles
x = if close > open
    close
else
    open  

// This code doesn’t compile by trading view
// y = if close > open
//     close
// else
//     "open"
plot(x)

可以省略else块。在这种情况下,如果条件为false,则会为var_declarationX变量分配一个“empty”值(na、false 或“”):

例子

// if
x = if close > open
    close
// If current close > current open, then x = close.
// Otherwise the x = na.
plot(x)

可以使用多个“else if”块或根本不使用。“then”、“else if”、“else”的块被移动四个空格:

例子

// if
x = if open > close
    5
else if high > low
    close
else
    open
plot(x)

可以忽略if语句的结果值(“var_declarationX=”可以省略)。如果您需要表达式的副作用,它可能很有用,例如在策略交易中:

例子

if (ta.crossover(high, low))
    strategy.entry("BBandLE", strategy.long, stop=low)
else
    strategy.cancel(id="BBandLE")

If语句可以相互包含:

例子

// if
float x = na
if close > open
    if close > close[1]
        x := close
    else
        x := close[1]
else
    x := open
plot(x)

for

'for'结构允许重复执行多个语句:

[var_declaration =] for counter = from_num to to_num [by step_num]
    statements | continue | break
    return_expression

var_declaration - 一个可选的变数声明,它将被指派为回圈的 return_expression 的值。
counter - 保存回圈计数器值的变数,在回圈的每次迭代中递增/递减 1 或 step_num 值。
from_num - 计数器的起始值。允许使用“series int/float”值/表达式。
to_num - 计数器的最终值。当计数器大于to_num(或小于to_num在from_num > to_num的情况下)时,循环中断。允许使用“series int/float”值/表达式,但它们仅在循环的第一次迭代时进行评估。
step_num - 计数器的递增/递减值。它是可选的。默认值为+1或-1,具体取决于from_num或to_num中最大的一个。使用值时,计数器也会根据from_num或to_num中最大的那个而递增/递减,因此step_num的+/-符号是可选的。
statements | continue | break - 任意数量的语句,或'continue'或'break'关键字,缩进4个空格或一次 tab。
return_expression - 循环的返回值,如果存在,则分配给var_declaration中的变量。 如果循环由于“continue”或“break”关键字而退出,则循环的返回值是在循环退出之前分配值的最后一个变量的返回值。
continue - 只能在回圈中使用的关键字。它导致回圈的下一次迭代被执行。
break - 退出回圈的关键字。

例子

// Here, we count the quantity of bars in a given 'lookback' length which closed above the current bar's close
qtyOfHigherCloses(lookback) =>
    int result = 0
    for i = 1 to lookback
        if close[i] > close
            result += 1
    result
plot(qtyOfHigherCloses(14))

另见
for...in while

for...in

for...in 结构允许为数组中的每个元素重复执行多个语句。它可以与任一参数一起使用:array_element,或与两个参数一起使用:[index, array_element]。 第二种形式不影响循环的功能。它在元组的第一个变量中跟踪当前迭代的索引。

[var_declaration =] for array_element in array_id
    statements | continue | break
    return_expression

[var_declaration =] for [index, array_element] in array_id
    statements | continue | break
    return_expression

var_declaration - 一个可选的变量声明,将被赋予循环的 return_expression 的值。
index - 跟踪当前迭代索引的可选变量。索引从 0 开始。变量在循环体中是不可变的。使用时,它必须包含在一个也包含 array_element 的元组中。
array_element - 包含要在循环中处理的每个连续阵列元素的变量。该变量在循环体中是不可变的。
array_id - 回圈迭代的阵列ID。
statements | continue | break - 任意数量的语句,或'continue'或'break'关键字,缩进4个空格或一次 tab。
return_expression - 循环的返回值分配给 var_declaration 中的变量,如果存在的话。 如果循环由于'continue'或'break'关键字而退出,则循环的返回值是循环退出前最后一个赋值的变量。
continue - 只能在回圈中使用的关键字。它导致回圈的下一次迭代被执行。
break - 退出回圈的关键字。

允许在循环内修改阵列的元素或其大小。
在这里,我们使用 for...in 的单参数形式来确定在每个K线上,有多少K线的OHLC值大于'close'值的SMA:

例子

// Here we determine on each bar how many of the bar's OHLC values are greater than the SMA of 'close' values
float[] ohlcValues = array.from(open, high, low, close)
qtyGreaterThan(value, array) =>
    int result = 0
    for currentElement in array
        if currentElement > value
            result += 1
        result
plot(qtyGreaterThan(ta.sma(close, 20), ohlcValues))

在这里,我们使用for...in的两个参数形式将我们的 isPos 数组的值设置为 true,当它们在我们的 valuesArray 数组中的对应值为正时:

例子

// for...in
var valuesArray = array.from(4, -8, 11, 78, -16, 34, 7, 99, 0, 55)
var isPos = array.new_bool(10, false)  

for [index, value] in valuesArray
    if value > 0
        array.set(isPos, index, true)  

if barstate.islastconfirmedhistory
    runtime.log(str.tostring(isPos))

另见
for while array.sum array.min array.max

while

while语句允许本地代码块的条件迭代。

variable_declaration = while boolean_expression
    ...
    continue
    ...
    break
    ...
    return_expression

说明:
variable_declaration - 可选的变量声明。return expression可以为这个变量提供初始化值。
boolean_expression - 如果为true,则执行while语句的本地块。如果为false,则在while语句之后继续执行脚本。
continue - continue 关键字导致循环分支到下一次迭代。
break - break 关键字导致循环终止。脚本的执行在 while 语句之后恢复。
return_expression - 提供 while 语句返回值的可选行。

例子

// This is a simple example of calculating a factorial using a while loop.
int i_n = input.int(10, "Factorial Size", minval=0)
int counter   = i_n
int factorial = 1
while counter > 0
    factorial := factorial * counter
    counter   := counter - 1

plot(factorial)

备注
初始 while 行之后的本地代码块必须缩进四个空格或一个制表符。要终止 while 循环,while 后面的布尔表达式必须最终变为 false,或者必须执行 break

switch

switch运算符根据条件和表达式的值将控制权转移到几个语句之一。

[variable_declaration = ] switch expression
    value1 => local_block
    value2 => local_block
    ...
    => default_local_block

[variable_declaration = ] switch
    boolean_expression1 => local_block
    boolean_expression2 => local_block
    ...
    => default_local_block

带表达式的switch:

例子

// Switch using an expression

string i_maType = input.string("EMA", "MA type", options = ["EMA", "SMA", "RMA", "WMA"])

float ma = switch i_maType
    "EMA" => ta.ema(close, 10)
    "SMA" => ta.sma(close, 10)
    "RMA" => ta.rma(close, 10)
    // Default used when the three first cases do not match.
    => ta.wma(close, 10)

plot(ma)

不带表达式的switch:

例子

strategy("Switch without an expression", overlay = true)

bool longCondition  = ta.crossover( ta.sma(close, 14), ta.sma(close, 28))
bool shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))

switch
    longCondition  => strategy.entry("Long ID", strategy.long)
    shortCondition => strategy.entry("Short ID", strategy.short)

返回值
执行的本地语句块中最后一个表达式的值。

备注
只能执行local_block实例或default_local_block之一。default_local_block仅与=>标记一起引入,并且仅在没有执行前面的块时才执行。如果switch语句的结果被分配给一个变量并且没有指定default_local_block,如果没有执行local_block,则该语句返回na。将switch语句的结果分配给变量时,所有local_block实例必须返回相同类型的值。

另见
if ?:

series

series是一个关键字,表示数据系列类型。显式使用 series 关键字通常是不必要的。

运算符

=

用于给变量赋值,但仅在声明变量时(第一次使用)。

:=

赋值运算符,给左侧变量赋值。用于为先前声明的变量赋值。

!=

不等于。适用于任何类型的表达式。

expr1 != expr2

返回值
布尔值,或一系列布尔值。

%

模数(整数余数)。 适用于数值表达式。

expr1 % expr2

返回值
整数或浮点值,或一系列值。

备注
在Pine脚本中,当计算整数的余数时,商将被截断。 即,将其四舍五入到最小绝对值。 所得值将具有与股息相同的符号。

示例:-1 % 9 = -1 - 9 * truncate(-1/9) = -1 - 9 * truncate(-0.111) = -1 - 9 * 0 = -1。

%=

模数指派。适用于数值表达式。

expr1 %= expr2

例子

// Equals to expr1 = expr1 % expr2.
a = 3
b = 3
a %= b
// Result: a = 0.
plot(a)

返回值
整数或浮点值,或一系列值。

*

乘法。适用于数值表达式。

expr1 * expr2

返回值
整数或浮点值,或一系列值。

*=

乘法指派。适用于数值表达式。

expr1 *= expr2

例子

// Equals to expr1 = expr1 * expr2.
a = 2
b = 3
a *= b
// Result: a = 6.
plot(a)

返回值
整数或浮点值,或一系列值。

+

添加或一元正号。适用于数值表达式或字符串。

expr1 + expr2
+ expr

返回值
字符串的二进制+返回expr1和expr2的合并
数字返回整数或浮点值,或一系列值:
二进制'+'返回expr1加expr2。
一元“+”返回expr(对一元运算符对称不添加任何内容)。

备注
您可以使用带数字的算术运算符以及变量数列。 在使用数列的情况下,操作符应用于元素。

+=

加法指派。适用于数值表达式或字符串。

expr1 += expr2

例子

// Equals to expr1 = expr1 + expr2.
a = 2
b = 3
a += b
// Result: a = 5.
plot(a)

返回值
对于字符串,返回expr1和expr2的串联。对于数字,返回整数或浮点值,或一系列值。

备注
您可以使用带数字的算术运算符以及变量数列。 在使用数列的情况下,操作符应用于元素。

-

减法或一元负号。 适用于数值表达式。

expr1 - expr2
- expr

返回值
返回整数或浮点值,或一系列值:
二进制'+'返回expr1减expr2。
一元的-返回expr的否定式。

备注
您可以使用带数字的算术运算符以及变量数列。 在使用数列的情况下,操作符应用于元素。

-=

减法指派。适用于数值表达式。

expr1 -= expr2

例子

// Equals to expr1 = expr1 - expr2.
a = 2
b = 3
a -= b
// Result: a = -1.
plot(a)

返回值
整数或浮点值,或一系列值。

/

除法。适用于数值表达式。

expr1 / expr2

返回值
整数或浮点值,或一系列值。

/=

除法指派。适用于数值表达式。

expr1 /= expr2

例子

// Equals to expr1 = expr1 / expr2.
a = 3
b = 3
a /= b
// Result: a = 1.
plot(a)

返回值
整数或浮点值,或一系列值。

<

小于。适用于数值表达式。

expr1 < expr2

返回值
布尔值,或一系列布尔值。

<=

小于或等于。适用于数值表达式。

expr1 <= expr2

返回值
布尔值,或一系列布尔值。

==

等于。 适用于任何类型的表达。

expr1 == expr2

返回值
布尔值,或一系列布尔值。

=>

'=>'运算符用于用户定义的函数声明和switch语句中。

函数声明语法是:

<identifier>([<parameter_name>[=<default_value>]], ...) =>
    <local_block>
    <function_result>

一个<local_block>是零个或多个Pine语句。
<function_result>是一个变量、一个表达式或一个元组。

例子

// single-line function
f1(x, y) => x + y
// multi-line function
f2(x, y) => 
    sum = x + y
    sumChange = ta.change(sum, 10)
    // Function automatically returns the last expression used in it
plot(f1(30, 8) + f2(1, 3))

备注
您可以在用户手册的声明函数和脚本库页面中了解有关用户定义函数的更多信息。

>

大于。适用于数值表达式。

expr1 > expr2

返回值
布尔值,或一系列布尔值。

>=

大于或等于。适用于数值表达式。

expr1 >= expr2

返回值
布尔值,或一系列布尔值。

?:

三元条件运算符。

expr1 ? expr2 : expr3

例子

// Draw circles at the bars where open crosses close
s2 = ta.cross(open, close) ? math.avg(open,close) : na
plot(s2, style=plot.style_circles, linewidth=2, color=color.red)  

// Combination of ?: operators for 'switch'-like logic
c = timeframe.isintraday ? color.red : timeframe.isdaily ? color.green : timeframe.isweekly ? color.blue : color.gray
plot(hl2, color=c)

返回值
如果expr1被评估为true,则expr2,否则为expr3。 零值(0和NaN,+ Infinity,-Infinity)被视为false,其他值皆为true。

备注
如果您不需要,请使用na作为“else”分支。
您可以结合使用两个或多个?:运算符,以实现类似于“switch”的语句(请参见上面的示例)。
您可以使用带数字的算术运算符以及变量数列。 在使用数列的情况下,操作符应用于元素。

另见
na

[]

系列下标。 提供对expr1系列的以前值的访问。 expr2是过去k线的数目,必须是数值。 浮动将被向下舍入。

expr1[expr2]

例子

// [] can be used to "save" variable value between bars
a = 0.0 // declare `a`
a := a[1] // immediately set current value to the same as previous. `na` in the beginning of history
if high == low // if some condition - change `a` value to another
    a := low
plot(a)

返回值
一系列数值。

另见
math.floor

and

逻辑 AND。适用于布尔表达式。

expr1 and expr2

返回值
布尔值,或一系列布尔值。

or

逻辑 OR。适用于布尔表达式。

expr1 or expr2

返回值
布尔值,或一系列布尔值。

not

逻辑求反(NOT)。 适用于布尔表达式。

not expr1

返回值
布尔值,或一系列布尔值。

数据类型关键字

bool

用于显式声明变量或参数的“bool”(布尔)类型的关键字。"Bool"变量的值可以是true、false或na。

例子

// bool
bool b = true    // Same as `b = true`
b := na
plot(b ? open : close)

备注
在变量声明中明确提及类型是可选的,除非它是用na初始化的。在 类型系统的用户手册页面中了解有关Pine类型的更多信息。

另见
var varip int float color string true false

int

用于显式声明变量或参数的“int”(整数)类型的关键字。

例子

// int
int i = 14    // Same as `i = 14`
i := na
plot(i)

备注
在变量声明中明确提及类型是可选的,除非它是用na初始化的。在 类型系统的用户手册页面中了解有关Pine类型的更多信息。

另见
var varip float bool color string

float

用于显式声明变量或参数的“float”(浮点)类型的关键字。

例子

// float
float f = 3.14    // Same as `f = 3.14`
f := na
plot(f)

备注
在变量声明中明确提及类型是可选的,除非它是用na初始化的。

另见
var varip int bool color string

string

用于显式声明变量或参数的"string"类型的关键字。

例子

// string
string s = "Hello World!"    // Same as `s = "Hello world!"`
// string s = na // same as "" 
plot(na, title=s)

备注
在变量声明中明确提及类型是可选的,除非它是用na初始化的。在 类型系统的用户手册页面中了解有关Pine类型的更多信息。

另见
var varip int float bool str.tostring str.format

color

用于显式声明变量或参数的"color"类型的关键字。

例子

// color
color textColor = color.green
if barstate.islastconfirmedhistory
    runtime.log("test", textcolor = textColor)

备注
颜色文字具有以下格式:#RRGGBB 或 #RRGGBBAA。 字母对代表00到FF的十六进制值(十进制的0到255),其中RR、GG和BB对是颜色的红色、绿色和蓝色分量的值。AA是颜色透明度(或alpha分量)的可选值,其中00不可见,FF不透明。 当没有提供AA对时,使用FF。十六进制字母可以是大写或小写。
在变量声明中明确提及类型是可选的,除非它是用na初始化的。在 类型系统的用户手册页面中了解有关Pine类型的更多信息。

另见
var varip int float string color.rgb color.new

array

用于显式声明变量或参数的“阵列”类型的关键字。可以使用array.new<type>,array.from函数创建阵列对象(或ID)。

例子

// array
array<float> a = na
a := array.new<float>(1, close)
plot(array.get(a, 0))

备注
阵列对象总是“系列”形式。

另见
var array.new array.from

内置函数

调用函数时传参数,可以指定参数名赋值,可以在对应的参数位置直接传入变量,也支持混合使用。例如:

plot(close, title="test plot")     // 直接传参数 close ;指定参数 title ,赋值字符串"test plot"

指定参数名赋值之后,就不能再直接传变量作为参数了,之后的传参都必须写成参数名赋值的形式。

// plot(close, title="test", color.red)    // 虽然plot第三个参数是颜色值,但是这样写就会报错
plot(close, title="test", color=color.red) // 正确写法
plot(close, "test", color.red)             // 正确写法

timeframe

timeframe.in_seconds

将传递给 timeframe 参数的时间周期转换为秒。

timeframe.in_seconds(timeframe)

例子

// Get chart timeframe:
i_tf = input.timeframe("1D")

// Convert timeframe to the int value (number of seconds in 1 Day):
tf = timeframe.in_seconds(i_tf)

plot(tf)

返回值
timeframe 的一根K线中的秒数的 int 表示形式。

参数

  • timeframe (simple string) 时间周期。可选。默认值为timeframe.period。

备注
对于 timeframe >= '1M' 函数根据一个月中的 30.4167 (365/12) 天计算秒数。

另见
input.timeframe timeframe.period

ticker

ticker.heikinashi

创建一个代码标识符请求平滑平均K线值。

ticker.heikinashi(symbol)

例子

heikinashi_close = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)

heikinashi_aapl_60_close = request.security(ticker.heikinashi(syminfo.tickerid), "60", close)
plot(heikinashi_close)
plot(heikinashi_aapl_60_close)

返回值
股票代码的字符串值,可以提供给request.security函数。

参数

  • symbol (simple string) 商品代码标识符。

另见
syminfo.tickerid syminfo.ticker request.security

request

request.security

要求另一个品种/解析度。

request.security(symbol, timeframe, expression, gaps, lookahead, ignore_invalid_symbol, currency) 

例子

s = request.security(syminfo.tickerid, "D", close)   // 1 Day
plot(s)

expr = ta.sma(close, 10)
s1 = request.security(syminfo.tickerid, "240", expr) // 240 Minutes
plot(s1)

// To avoid difference in calculation on history/realtime you can request not latest values and use merge strategy flags as follows:
s2 = request.security(syminfo.tickerid, "D", close[1], barmerge.gaps_off, barmerge.lookahead_on)
plot(s2)
f() => [open, high]
[o, h] = request.security(syminfo.tickerid, "D", f())
[l, c] = request.security(syminfo.tickerid, "D", [low, close])
plot((o + h + l + c) / 4)

返回值
要求系列

参数

  • symbol (simple string) 商品代码。
  • timeframe (simple string) 时间周期。空字符串将被解释为图表的当前时间周期。
  • expression (series int/float/bool/color) 可以从request.security调用计算并返回一个表达式。它可以是一个系列或一个包含可以转换为系列的元素的元组。
  • gaps (barmerge_gaps) 给所请求的数据合并策略(要求数据自动与主要系列OHLC数据合并)。 可能的值:barmerge.gaps_on,barmerge.gaps_off。 barmerge.gaps_on - 请求的数据与可能差距合并(na值)。 barmerge.gaps_off - 请求的数据连续不间断地合并,所有的差距都填满了之前最近的现有值。 默认值为barmerge.gaps_off。
  • lookahead (barmerge_lookahead) 给所请求的数据合并策略。可能的值:barmerge.lookahead_on,barmerge.lookahead_off。 从版本3开始,默认值为barmerge.lookahead_off。请注意,行为与实时相同,仅在历史上不同。
  • ignore_invalid_symbol (const bool) 一个可选参数。如果未找到指定的商品,则确定函数的行为:如果为 false,脚本将停止并返回运行时错误; 如果为true,函数将返回na并继续执行。默认值为false。
  • currency (simple string) 将商品的货币相关值(例如 OHLC)转换成的货币。然后根据转换后的值计算“expression”。使用的转换率基于FX_IDC对的前一天的每日汇率(相对于进行计算的K线)。可选。默认值为syminfo.currency。可能的值:带有 ISO 4217格式的货币代码(例如“USD”)的三字母字符串或 currency.* 命名空间中的常量之一,例如currency.USD。

备注
使用此功能的PineScript代码可以对历史记录和实时数据进行不同的计算。
如果您想为请求的商品指定附加参数,例如交易时段或调整类型,您可以使用ticker.new()函数。
无法使用'ticker'变量将点差传递给此函数。您可以使用'ticker.new'变量或股票代码的字符串表示形式,例如“AAPL+MSFT*TSLA”。
目前,一个脚本中最多可以有40个request.security调用。
请注意,使用此变量/函数可能会导致指标重新绘制。
分辨率参数允许值为:
1S,5S,15S,30S - 秒间隔(图表周期应小于或等于请求的周期)
从1到1440分钟
从1D到365D天
从1W到52W几周
从1M到12M几个月

另见
syminfo.ticker syminfo.tickerid timeframe.period ta.correlation barmerge.lookahead_off barmerge.lookahead_on

str

str.contains

如果source字符串包含str子字符串,则返回true,否则返回false。

str.contains(source, str)

例子

// If the current chart is a continuous futures chart, e.g “BTC1!”, then the function will return true, false otherwise.
var isFutures = str.contains(syminfo.tickerid, "!")
plot(isFutures ? 1 : 0)

返回值
如果在source字符串中找到 str,则为true ,否则为false。

参数

  • source (series string) 来源字符串
  • str (series string) 要搜索的子字符串。

另见
str.pos str.match

str.endswith

如果source字符串以str中指定的子字符串结尾,则返回true,否则返回false。

str.endswith(source, str)

返回值
如果source字符串以str中指定的子字符串结尾,则为true,否则为false。

参数

  • source (series string) 来源字符串
  • str (series string) 要搜索的子字符串。

另见
str.startswith

str.startswith

如果source字符串以str中指定的子字符串开头,则返回true,否则返回false。

str.startswith(source, str)

返回值
如果source字符串以str中指定的子字符串开头,则为true,否则为false。

参数

  • source (series string) 来源字符串
  • str (series string) 要搜索的子字符串。

另见
str.endswith

str.substring

返回一个新字符串,它是source字符串的子字符串。子字符串以begin_pos 指定的索引处的字符开始,并扩展到source 字符串的'end_pos - 1'。

str.substring(source, begin_pos)
str.substring(source, begin_pos, end_pos)

例子

sym= "EXCHANGE_NAME:SYMBOL_NAME"
pos = str.pos(sym, ":")        // Get position of ":" character
tkr= str.substring(sym, pos+1) // "SYMBOL_NAME"
if barstate.islastconfirmedhistory
    runtime.log(tkr)

返回值
从源字符串中提取的子字符串。

参数

  • source (series string) 从中提取子字符串的源字符串。
  • begin_pos (series int) 提取的子串的起始位置。它是独占的(提取的子字符串包括该位置的字符)。
  • end_pos (series int) 结束位置。它是独占的(提取的字符串不包括该位置的字符)。可选。默认值为source字符串的长度。

备注
字符串索引从0开始。如果begin_pos等于end_pos,函数返回一个空字符串。

另见
str.contains str.pos str.match

str.tonumber

str.tonumber(string)

返回值
如果包含有效数字,为字符串的浮点型,否则为na。

参数

  • string (series string) int或float的字符串表现形式。

str.format

将格式字符串和值转换为格式化字符串。格式字符串可以包含文字文本和每个要格式化的值的大括号{}中的一个占位符。每个占位符包括将替换它的必需参数的指数(从0开始) ,以及一个可选的格式说明符。索引表示该参数在str.format参数列表中的位置。

str.format(formatString, arg0, arg1, ...)

例子

// The format specifier inside the curly braces accepts certain modifiers:
// - Specify the number of decimals to display:
s1 = str.format("{0,number,#.#}", 1.34) // returns: 1.3
runtime.log(s1)

// - Round a float value to an integer:
s2 = str.format("{0,number,integer}", 1.34) // returns: 1
runtime.log(s2)

// - Display a number in currency:
s3 = str.format("{0,number,currency}", 1.34) // returns: $1.34
runtime.log(s3)

// - Display a number as a percentage:
s4 = str.format("{0,number,percent}", 0.5) // returns: 50%
runtime.log(s4)

// EXAMPLES WITH SEVERAL ARGUMENTS
// returns: Number 1 is not equal to 4
s5 = str.format("Number {0} is not {1} to {2}", 1, "equal", 4)
runtime.log(s5)

// returns: 1.34 != 1.3
s6 = str.format("{0} != {0, number, #.#}", 1.34)
runtime.log(s6)

// returns: 1 is equal to 1, but 2 is equal to 2
s7 = str.format("{0, number, integer} is equal to 1, but {1, number, integer} is equal to 2", 1.34, 1.52)
runtime.log(s7)

// returns: The cash turnover amounted to $1,340,000.00
s8 = str.format("The cash turnover amounted to {0, number, currency}", 1340000)
runtime.log(s8)

// returns: Expected return is 10% - 20%
s9 = str.format("Expected return is {0, number, percent} - {1, number, percent}", 0.1, 0.2)
runtime.log(s9)

返回值
格式化的字符串。

参数

  • formatString (series string) 格式字符串。
  • arg0, arg1, ... (series int/float/bool/string/na/int[]/float[]/bool[]/string[]) 要格式化的值。

备注
未引用样式中的所有花括号必须保持平衡。例如,"ab {0} de"和"ab '}' de"是有效的样式 ,但是"ab {0'}' de", "ab } de"和"''{''"不是有效样式。

str.length

返回与该字符串中的字符数相对应的整数。

str.length(string)

返回值
源字符串中的字符数。

参数

  • string (series string) 来源字符串

str.lower

返回一个所有字母都转换为小写的新字符串。

str.lower(source)

返回值
所有字母都转换为小写的新字符串。

参数

  • source (series string) 要转换的字符串。

另见
str.upper

str.upper

返回一个所有字母都转换为大写的新字符串。

str.upper(source)

返回值
所有字母都转换为大写的新字符串。

参数

  • source (series string) 要转换的字符串。

另见
str.lower

str.match

如果匹配regex正则表达式,则返回source字符串的新子字符串,否则返回'na'。

str.match(source, regex) 

例子

s = input.string("It's time to sell some EXCHANGE_NAME:SYMBOL_NAME!")

// finding first substring that matches regular expression "[\w]+:[\w]+"
var string tickerid = str.match(s, "[\\w]+:[\\w]+")

if barstate.islastconfirmedhistory
    runtime.log(tickerid) // "EXCHANGE_NAME:SYMBOL_NAME"

返回值
source字符串的新子字符串,如果它匹配一个regex正则表达式,否则为'na'。

参数

  • source (series string) 来源字符串
  • regex (series string) 与此字符串匹配的正则表达式。

备注
函数返回source字符串中第一次出现的正则表达式。
regex字符串中的反斜杠“\”符号需要使用额外的反斜杠进行转义,例如“\d”代表正则表达式“\d”。

另见
str.contains str.substring

str.pos

返回source字符串中第一次出现str字符串的位置,否则返回'na'。

str.pos(source, str)

返回值
str字符串在source字符串中的位置。

参数

  • source (series string) 来源字符串
  • str (series string) 要搜索的子字符串。

备注
字符串索引从0开始。

另见
str.contains str.match str.substring

str.replace

返回一个新字符串,其中第N+1次出现的target字符串以及以前出现的target字符串替换为replacement字符串,其中N在occurrence中指定。N为要替换的目标字符串在来源字符串中出现的匹配索引。

str.replace(source, target, replacement, occurrence)

例子

var source = "EXCHANGE1:SYMBOL1 / EXCHANGE1:SYMBOL2"

// Replace first occurrence of "EXCHANGE1" with "EXCHANGE2" replacement string
var newSource = str.replace(source, "EXCHANGE1",  "EXCHANGE2", 0)

if barstate.islastconfirmedhistory
    // Display "EXCHANGE2:SYMBOL1 / EXCHANGE1:SYMBOL2"
    runtime.log(newSource)

返回值
已处理字符串

参数

  • source (series string) 来源字符串
  • target (series string) 被替换字符串
  • replacement (series string) 要插入的字符串而不是目标字符串。
  • occurrence (series int) 要替换的目标字符串在来源字符串中出现的匹配索引。第一个匹配的索引从0开始。可选。默认值为0。

另见
str.replace_all str.match

str.replace_all

用替换字符串,替换源字符串中每次出现的目标字符串。

str.replace_all(source, target, replacement)

返回值
已处理字符串

参数

  • source (series string) 来源字符串
  • target (series string) 被替换字符串
  • replacement (series string) 每次出现的目标字串都将替换的字串

str.split

将字符串划分为子字符串阵列,并返回其阵列ID。

str.split(string, separator)

返回值
字符串阵列的ID。

参数

  • string (series string) 来源字符串
  • separator (series string) 分隔每个子字符串的字符串。

str.tostring

str.tostring(value)
str.tostring(value, format)
str.tostring(value[])
str.tostring(value[], format)

返回值
value参数的字符串表示形式。
如果value参数是字符串,则按原样返回。
value为na时,函数返回字符串“NaN”。

参数

  • value (series int/float/bool/string/int[]/float[]/bool[]/string[]) 其元素转换为字符串的值或数组ID。
  • format (series string) Format string. Accepts these format.* constants: format.mintick, format.percent, format.volume. Optional. The default value is '#.##########'.

备注
浮点值的格式也会在必要时四舍五入这些值,例如str.tostring(3.99, '#') 将返回“4”。
要显示尾随零,请使用'0'而不是'#'。例如,'#.000'。
使用format.mintick时,该值将四舍五入到可以除以syminfo.mintick而没有余数的最接近的数字。返回的字符串带有尾随零。
如果x参数是字符串,则将返回相同的字符串值。
Bool类型参数返回“true”或“false”。
当x为na时,函数返回“NaN”。

color

color.new

功能颜色将指定透明度应用于给定的颜色。

color.new(color, transp)

例子

plot(close, color=color.new(color.red, 50))

返回值
有特定透明度的颜色。

参数

  • color (series color)
  • transp (series int/float) 可用的值是从0(不透明)到100(不可见)

备注
使用非常数的参数(例如,“simple”、“input”或“series”)将对脚本“设置/样式”标签页中显示的颜色产生影响。请参阅用户手册了解更多信息。

color.rgb

使用RGB颜色模型创建带有透明度的新颜色。

color.rgb(red, green, blue, transp)

例子

plot(close, color=color.rgb(255, 0, 0, 50))

返回值
有特定透明度的颜色。

参数

  • red (series int/float) 红色调。可能的值是从0到255。
  • green (series int/float) 绿色调。可能的值是从0到255。
  • blue (series int/float) 蓝色调。可能的值是从0到255。
  • transp (series int/float) 可选。颜色透明。可能的值从0(不透明)到100(透明)。默认值为0。

备注
使用非常数的参数(例如,“simple”、“input”或“series”)将对脚本“设置/样式”标签页中显示的颜色产生影响。请参阅用户手册了解更多信息。

runtime

runtime.debug

在控制台打印变量信息。

FMZ PINE语言特有函数,runtime.debug(value),只有一个参数。

runtime.log

在日志输出内容。

FMZ PINE语言特有函数,runtime.log(1, 2, 3, close, high, ...),可以传多个参数。

runtime.error

调用时,会导致运行时错误,并带有在message参数中指定的错误消息。

runtime.error(message)

参数
message (series string) 错误消息。

input

input

将input添加到脚本设置的输入标签页,它允许您向脚本用户提供配置选项。此函数自动检测用于“defval”的参数类型并使用相应的输入插件。

input(defval, title, tooltip, inline, group)
input(defval, title, inline, group, tooltip)

例子

i_switch = input(true, "On/Off")     // 设置true,默认勾选
plot(i_switch ? open : na)

i_len = input(7, "Length")
i_src = input(close, "Source")       // 下拉框,默认选择close
plot(ta.sma(i_src, i_len))

i_col = input(color.red, "Plot Color")
plot(close, color=i_col)

i_text = input("Hello!", "Message")
runtime.log(i_text)

返回值
输入变量值

参数

  • defval (const int/float/bool/string/color or source-type built-ins) 确定脚本的“设置/输入”标签页中建议的输入变量的默认值,脚本用户可以从中更改它。源类型内置函数是指定计算源的内置系列浮点变量:closehlc3 等。
  • title (const string) 输入的标题。如果未指定,则将变量名用作输入的标题。如果指定了标题,但标题为空,则名称将为空字符串。
  • tooltip (const string) 此字符串将在鼠标悬停在工具提示图标上时显示给用户。
  • inline (const string) 在一行中使用相同的参数合并所有输入调用。不显示用作参数的字符串。它仅用于辨识属于同一行的输入。
  • group (const string) 使用相同的组参数字符串在所有输入上方创建标头。该字符串也用作标头的文本。

备注
input函数的返回值应始终分配给变量。见上面的例子

另见
input.bool input.color input.int input.float input.string input.timeframe input.source

input.source

将input添加到脚本设置的输入标签页,它允许您向脚本用户提供配置选项。此功能添加了一个下拉菜单,允许用户选择计算源,例如close、hl2等。如果脚本只包含一个input.source()调用,用户还可以选择图表上另一个指标的输出作为源。

input.source(defval, title, tooltip, inline, group)

例子

i_src = input.source(close, "Source")
plot(i_src)

返回值
输入变量值

参数

  • defval (series int/float) 确定脚本的“设置/输入”标签页中建议的输入变量的默认值,用户可以从中更改它。
  • title (const string) 输入的标题。如果未指定,则将变量名用作输入的标题。如果指定了标题,但标题为空,则名称将为空字符串。
  • tooltip (const string) 此字符串将在鼠标悬停在工具提示图标上时显示给用户。
  • inline (const string) 在一行中使用相同的参数合并所有输入调用。不显示用作参数的字符串。它仅用于辨识属于同一行的输入。
  • group (const string) 使用相同的组参数字符串在所有输入上方创建标头。该字符串也用作标头的文本。

备注
input.source函数的结果总是应该分配给一个变量,见上面的例子。

另见
input.bool input.int input.float input.string input.timeframe input.color input

input.string

将input添加到脚本设置的输入选项卡,它允许您向脚本用户提供配置选项。此函数将字符串输入字段添加到脚本的输入中。

input.string(defval, title, options, tooltip, inline, group, confirm)

例子

i_text = input.string("Hello!", "Message")
runtime.log(i_text)

返回值
输入变量值

参数

  • defval (const string) 确定脚本的“设置/输入”标签页中建议的输入变量的默认值,用户可以从中更改它。当值列表与options参数一起使用时,该值必须是其中之一。
  • title (const string) 输入的标题。如果未指定,则将变量名用作输入的标题。如果指定了标题,但标题为空,则名称将为空字符串。
  • options (List of constants: [<type>...]) 可供选择的选项列表。
  • tooltip (const string) 此字符串将在鼠标悬停在工具提示图标上时显示给用户。
  • inline (const string) 在一行中使用相同的参数合并所有输入调用。不显示用作参数的字符串。它仅用于辨识属于同一行的输入。
  • group (const string) 使用相同的组参数字符串在所有输入上方创建标头。该字符串也用作标头的文本。
  • confirm (const bool) 如果为true,则在将指标添加到图表之前,将要求用户确认输入值。默认值为false。

备注
input.string函数的结果总是应该分配给一个变量,见上面的例子。

另见
input.bool input.int input.float input.timeframe input.source input.color input

input.bool

将input添加到脚本设置的输入标签页,它允许您向脚本用户提供配置选项。此函数为脚本的输入添加复选标记。

input.bool(defval, title, tooltip, inline, group, confirm)

例子

i_switch = input.bool(true, "On/Off")
plot(i_switch ? open : na)

返回值
输入变量值

参数

  • defval (const bool) 确定脚本的“设置/输入”标签页中建议的输入变量的默认值,用户可以从中更改它。
  • title (const string) 输入的标题。如果未指定,则将变量名用作输入的标题。如果指定了标题,但标题为空,则名称将为空字符串。
  • tooltip (const string) 此字符串将在鼠标悬停在工具提示图标上时显示给用户。
  • inline (const string) 在一行中使用相同的参数合并所有输入调用。不显示用作参数的字符串。它仅用于辨识属于同一行的输入。
  • group (const string) 使用相同的组参数字符串在所有输入上方创建标头。该字符串也用作标头的文本。
  • confirm (const bool) 如果为true,则在将指标添加到图表之前,将要求用户确认输入值。默认值为false。

备注
input.bool函数的结果总是应该分配给一个变量,见上面的例子。

另见
input.int input.float input.string input.timeframe input.source input.color input

input.int

将input添加到脚本设置的输入标签页,它允许您向脚本用户提供配置选项。此函数将整数输入字段添加到脚本的输入中。

input.int(defval, title, minval, maxval, step, tooltip, inline, group, confirm) 
input.int(defval, title, options, tooltip, inline, group, confirm)

例子

i_len1 = input.int(10, "Length 1", minval=5, maxval=21, step=1)
plot(ta.sma(close, i_len1))

i_len2 = input.int(10, "Length 2", options=[5, 10, 21])
plot(ta.sma(close, i_len2))

返回值
输入变量值

参数

  • defval (const int) 确定脚本的“设置/输入”标签页中建议的输入变量的默认值,脚本用户可以从中更改它。当值列表与 options 参数一起使用时,该值必须是其中之一。
  • title (const string) 输入的标题。如果未指定,则将变量名用作输入的标题。如果指定了标题,但标题为空,则名称将为空字符串。
  • minval (const int) 输入变量的最小可能值。可选。
  • maxval (const int) 输入变量的最大可能值。可选。
  • step (const int) 用于增加/减少输入的步长值。可选。默认值为1。
  • options (tuple of const int values: [val1, val2, ...]) 从下拉菜单中选择的选项列表,以逗号分隔并用方括号括起来:[val1, val2, ...]。使用该参数时,不能使用minvalmaxvalstep参数。
  • tooltip (const string) 此字符串将在鼠标悬停在工具提示图标上时显示给用户。
  • inline (const string) 在一行中使用相同的参数合并所有输入调用。不显示用作参数的字符串。它仅用于辨识属于同一行的输入。
  • group (const string) 使用相同的组参数字符串在所有输入上方创建标头。该字符串也用作标头的文本。
  • confirm (const bool) 如果为true,则在将指标添加到图表之前,将要求用户确认输入值。默认值为false。

备注
input.int函数的结果总是应该分配给一个变量,见上面的例子。

另见
input.bool input.float input.string input.timeframe input.source input.color input

input.float

将input添加到脚本设置的输入标签页,它允许您向脚本用户提供配置选项。此函数将浮点输入字段添加到脚本的输入中。

input.float(defval, title, minval, maxval, step, tooltip, inline, group, confirm)
input.float(defval, title, options, tooltip, inline, group, confirm)

例子

i_angle1 = input.float(0.5, "Sin Angle", minval=-3.14, maxval=3.14, step=0.02)
plot(math.sin(i_angle1) > 0 ? close : open, "sin", color=color.green)

i_angle2 = input.float(0, "Cos Angle", options=[-3.14, -1.57, 0, 1.57, 3.14])
plot(math.cos(i_angle2) > 0 ? close : open, "cos", color=color.red)

返回值
输入变量值

参数

  • defval (const int/float) 确定脚本的“设置/输入”标签页中建议的输入变量的默认值,脚本用户可以从中更改它。当值列表与 options 参数一起使用时,该值必须是其中之一。
  • title (const string) 输入的标题。如果未指定,则将变量名用作输入的标题。如果指定了标题,但标题为空,则名称将为空字符串。
  • minval (const int/float) 输入变量的最小可能值。可选。
  • maxval (const int/float) 输入变量的最大可能值。可选。
  • step (const int/float) 用于增加/减少输入的步长值。可选。默认值为1。
  • options (tuple of const int/float values: [val1, val2, ...]) 从下拉菜单中选择的选项列表,以逗号分隔并用方括号括起来:[val1, val2, ...]。使用该参数时,不能使用minvalmaxvalstep参数。
  • tooltip (const string) 此字符串将在鼠标悬停在工具提示图标上时显示给用户。
  • inline (const string) 在一行中使用相同的参数合并所有输入调用。不显示用作参数的字符串。它仅用于辨识属于同一行的输入。
  • group (const string) 使用相同的组参数字符串在所有输入上方创建标头。该字符串也用作标头的文本。
  • confirm (const bool) 如果为true,则在将指标添加到图表之前,将要求用户确认输入值。默认值为false。

备注
input.float函数的结果总是应该分配给一个变量,见上面的例子。

另见
input.bool input.int input.string input.timeframe input.source input.color input

input.color

将input添加到脚本设置的输入标签页,它允许您向脚本用户提供配置选项。此函数添加了一个颜色选择器,允许用户从调色板或十六进制值中选择颜色和透明度。

input.color(defval, title, tooltip, inline, group, confirm) 

例子

i_col = input.color(color.red, "Plot Color")
plot(close, color=i_col)

返回值
输入变量值

参数

  • defval (const color) 确定脚本的“设置/输入”标签页中建议的输入变量的默认值,用户可以从中更改它。
  • title (const string) 输入的标题。如果未指定,则将变量名用作输入的标题。如果指定了标题,但标题为空,则名称将为空字符串。
  • tooltip (const string) 此字符串将在鼠标悬停在工具提示图标上时显示给用户。
  • inline (const string) 在一行中使用相同的参数合并所有输入调用。不显示用作参数的字符串。它仅用于辨识属于同一行的输入。
  • group (const string) 使用相同的组参数字符串在所有输入上方创建标头。该字符串也用作标头的文本。
  • confirm (const bool) 如果为true,则在将指标添加到图表之前,将要求用户确认输入值。默认值为false。

备注
input.color函数的结果总是应该分配给一个变量,见上面的例子。

另见
input.bool input.int input.float input.string input.timeframe input.source input

input.price

将价格输入添加到脚本的“设置/输入”标签页。使用 confirm = true 激活交互式输入模式,通过点击图表选择价格。

input.price(defval, title, tooltip, inline, group, confirm) 

例子

price1 = input.price(title="Date", defval=42)
plot(price1)

price2 = input.price(54, title="Date")
plot(price2)

返回值
输入变量值

参数

  • defval (const int/float) 确定脚本的“设置/输入”标签页中建议的输入变量的默认值,用户可以从中更改它。
  • title (const string) 输入的标题。如果未指定,则将变量名用作输入的标题。如果指定了标题,但标题为空,则名称将为空字符串。
  • tooltip (const string) 此字符串将在鼠标悬停在工具提示图标上时显示给用户。
  • inline (const string) 在一行中使用相同的参数合并所有输入调用。不显示用作参数的字符串。它仅用于辨识属于同一行的输入。
  • group (const string) 使用相同的组参数字符串在所有输入上方创建标头。该字符串也用作标头的文本。
  • confirm (const bool) 如果为true,则启用交互式输入模式,并通过在将指标添加到图表时点击图表来完成选择,或者通过选择指标并在此之后移动选择来完成选择。可选。默认值为false。

备注
使用交互模式时,如果两个函数调用对其 inline 参数使用相同的参数,则可以将时间输入与价格输入结合使用。

另见
input.bool input.int input.float input.string input.resolution input.source input.color input

input.timeframe

将input添加到脚本设置的输入标签页,它允许您向脚本用户提供配置选项。此函数添加一个下拉列表,允许用户通过时间周期选择器选择特定时间周期并将其作为字符串返回。选择器包括用户可能使用图表的时间周期下拉菜单添加的自定义时间周期。

input.timeframe(defval, title, options, tooltip, inline, group, confirm)

例子

i_res = input.timeframe('D', "Resolution", options=['D', 'W', 'M'])
s = request.security(syminfo.tickerid, i_res, close)
plot(s)

返回值
输入变量值

参数

  • defval (const string) 确定脚本的“设置/输入”标签页中建议的输入变量的默认值,用户可以从中更改它。当值列表与options参数一起使用时,该值必须是其中之一。
  • title (const string) 输入的标题。如果未指定,则将变量名用作输入的标题。如果指定了标题,但标题为空,则名称将为空字符串。
  • options (tuple of const string values: [val1, val2, ...]) 可供选择的选项列表。
  • tooltip (const string) 此字符串将在鼠标悬停在工具提示图标上时显示给用户。
  • inline (const string) 在一行中使用相同的参数合并所有输入调用。不显示用作参数的字符串。它仅用于辨识属于同一行的输入。
  • group (const string) 使用相同的组参数字符串在所有输入上方创建标头。该字符串也用作标头的文本。
  • confirm (const bool) 如果为true,则在将指标添加到图表之前,将要求用户确认输入值。默认值为false。

备注
input.timeframe函数的结果总是应该分配给一个变量,见上面的例子。

另见
input.bool input.int input.float input.string input.source input.color input

input.integer

暂无

input.resolution

暂无

ta

ta.alma

Arnaud Legoux移动平均线。 它使用高斯分布作为移动平均值的权重。

ta.alma(series, length, offset, sigma) 
ta.alma(series, length, offset, sigma, floor) 

例子

plot(ta.alma(close, 9, 0.85, 6))

// same on pine, but much less efficient
pine_alma(series, windowsize, offset, sigma) =>
    m = offset * (windowsize - 1)
    //m = math.floor(offset * (windowsize - 1)) // Used as m when math.floor=true
    s = windowsize / sigma
    norm = 0.0
    sum = 0.0
    for i = 0 to windowsize - 1
        weight = math.exp(-1 * math.pow(i - m, 2) / (2 * math.pow(s, 2)))
        norm := norm + weight
        sum := sum + series[windowsize - i - 1] * weight
    sum / norm
plot(pine_alma(close, 9, 0.85, 6))

返回值
Arnaud Legoux移动平均线

参数

  • series (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).
  • offset (simple int/float) 控制平滑度(更接近1)和响应性(更接近0)之间的权衡。
  • sigma (simple int/float) 改变ALMA的平滑度。Sigma越大,ALMA越平滑。
  • floor (simple bool) 可选参数。在计算ALMA之前,指定偏移量计算是否为下限。默认值为false。

另见
ta.sma ta.ema ta.rma ta.wma ta.vwma ta.swma

ta.sma

sma函数返回移动平均值,即x的最后y值,除以y。

ta.sma(source, length) 

例子

plot(ta.sma(close, 15))

// same on pine, but much less efficient
pine_sma(x, y) =>
    sum = 0.0
    for i = 0 to y - 1
        sum := sum + x[i] / y
    sum
plot(pine_sma(close, 15))

返回值
lengthK线返回的source的简单移动平均线。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

另见
ta.ema ta.rma ta.wma ta.vwma ta.swma ta.alma

ta.cog

cog(重心点)是基于统计学和斐波那契黄金比例的指标。

ta.cog(source, length) 

例子

plot(ta.cog(close, 10))

// the same on pine
pine_cog(source, length) =>
    sum = math.sum(source, length)
    num = 0.0
    for i = 0 to length - 1
        price = source[i]
        num := num + price * (i + 1)
    -num / sum

plot(pine_cog(close, 10))

返回值
重心

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

另见
ta.stoch

ta.dev

衡量系列与其ta.sma之间的差异

ta.dev(source, length) 

例子

plot(ta.dev(close, 10))

// the same on pine
pine_dev(source, length) =>
    mean = ta.sma(source, length)
    sum = 0.0
    for i = 0 to length - 1
        val = source[i]
        sum := sum + math.abs(val - mean)
    dev = sum/length
plot(pine_dev(close, 10))

返回值
lengthK线返回的source偏差。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

另见
ta.variance ta.stdev

ta.stdev

ta.stdev(source, length, biased) 

例子

plot(ta.stdev(close, 5))

//the same on pine
isZero(val, eps) => math.abs(val) <= eps

SUM(fst, snd) =>
    EPS = 1e-10
    res = fst + snd
    if isZero(res, EPS)
        res := 0
    else
        if not isZero(res, 1e-4)
            res := res
        else
            15

pine_stdev(src, length) =>
    avg = ta.sma(src, length)
    sumOfSquareDeviations = 0.0
    for i = 0 to length - 1
        sum = SUM(src[i], -avg)
        sumOfSquareDeviations := sumOfSquareDeviations + sum * sum

    stdev = math.sqrt(sumOfSquareDeviations / length)
plot(pine_stdev(close, 5))

返回值
标准差

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).
  • biased (series bool) 确定应该使用哪个估计。可选。默认值为true。

备注
如果biased为true,函数将使用对整个总体的有偏估计进行计算,如果为false - 对样本的无偏估计。

另见
ta.dev ta.variance

ta.ema

ema 函数返回指数加权移动平均线。在 ema 中,加权因子呈指数下降。它使用以下公式计算:EMA = alpha * source + (1 - alpha) * EMA[1],其中 alpha = 2 / (length + 1)。

ta.ema(source, length) 

例子

plot(ta.ema(close, 15))

//the same on pine
pine_ema(src, length) =>
    alpha = 2 / (length + 1)
    sum = 0.0
    sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1])
plot(pine_ema(close,15))

返回值
source 的指数移动平均线,alpha = 2 / (长度 + 1)。

参数

  • source (series int/float) 待执行的系列值。
  • length (simple int) K线数量(长度).

备注
请注意,使用此变量/函数可能会导致指标重新绘制。

另见
ta.sma ta.rma ta.wma ta.vwma ta.swma ta.alma

ta.wma

wma 函数返回 length K线的 source 的加权移动平均值。在 wma 中,加权因子以算术级数递减。

ta.wma(source, length) 

例子

plot(ta.wma(close, 15))

// same on pine, but much less efficient
pine_wma(x, y) =>
    norm = 0.0
    sum = 0.0
    for i = 0 to y - 1
        weight = (y - i) * y
        norm := norm + weight
        sum := sum + x[i] * weight
    sum / norm
plot(pine_wma(close, 15))

返回值
lengthK线返回的source加权移动平均线。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

另见
ta.sma ta.ema ta.rma ta.vwma ta.swma ta.alma

ta.swma

具有固定长度的对称加权移动平均线:4.权重:[1/6,2 / 6,2 / 6,1 / 6]。

ta.swma(source)

例子

plot(ta.swma(close))

// same on pine, but less efficient
pine_swma(x) =>
    x[3] * 1 / 6 + x[2] * 2 / 6 + x[1] * 2 / 6 + x[0] * 1 / 6
plot(pine_swma(close))

返回值
对称加权移动平均线。

参数

  • source (series int/float) 源系列。

另见
ta.sma ta.ema ta.rma ta.wma ta.vwma ta.alma

ta.hma

hma函数返回船体移动平均线HMA。

ta.hma(source, length)

例子

src = input(defval=close, title="Source")
length = input(defval=9, title="Length")
hmaBuildIn = ta.hma(src, length)
plot(hmaBuildIn, title="Hull MA", color=#674EA7)

返回值
返回 '​​length' 柱的 'source' 的船体移动平均线Hull Moving Average。

参数

  • source (series int/float) 待执行的系列值。
  • length (simple int) K线数量

另见
ta.ema ta.rma ta.wma ta.vwma ta.sma

ta.rma

RSI中使用的移动平均线。 它是指数加权移动平均线,alpha加权值 = 1 /长度。

ta.rma(source, length)

例子

plot(ta.rma(close, 15))

//the same on pine
pine_rma(src, length) =>
	alpha = 1/length
	sum = 0.0
	sum := na(sum[1]) ? ta.sma(src, length) : alpha * src + (1 - alpha) * nz(sum[1])
plot(pine_rma(close, 15))

返回值
source的指数移动平均线,alpha = 1 / length

参数

  • source (series int/float) 待执行的系列值。
  • length (simple int) K线数量(长度).

另见
ta.sma ta.ema ta.wma ta.vwma ta.swma ta.alma ta.rsi

ta.rsi

相对强度指数。它是使用在最后一个 length K线上source 的向上和向下变化的ta.rma() 计算的。

ta.rsi(source, length)

例子

plot(ta.rsi(close, 7))

// same on pine, but less efficient
pine_rsi(x, y) => 
    u = math.max(x - x[1], 0) // upward ta.change
    d = math.max(x[1] - x, 0) // downward ta.change
    rs = ta.rma(u, y) / ta.rma(d, y)
    res = 100 - 100 / (1 + rs)
    res

plot(pine_rsi(close, 7))

返回值
相对强弱指标(RSI)

参数

  • source (series int/float) 待执行的系列值。
  • length (simple int) K线数量(长度).

另见
ta.rma

ta.tsi

真实强弱指数。它使用金融工具潜在动量的移动平均线。

ta.tsi(source, short_length, long_length)

返回值
真实强弱指数。范围[-1,1]中的值。

参数

  • source (series int/float) 源系列。
  • short_length (simple int) 短的长度。
  • long_length (simple int) 长线长度。

ta.roc

函数 roc(变化率)显示 source 的当前值与 source 几天前的 length 值之间的差异。
由以下公式计算:100 * change(src, length) / src[length]。

ta.roc(source, length)

返回值
lengthK线返回的source的变化率。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

ta.range

返回序列中最小值和最大值之间的差。

ta.range(source, length)

返回值
序列中最小值和最大值之间的差。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

ta.macd

MACD(平滑异同平均线)。 它应该揭示股票价格趋势的实力、方向、动量和持续时间的变化。

ta.macd(source, fastlen, slowlen, siglen) 

例子

[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)
plot(macdLine, color=color.blue)
plot(signalLine, color=color.orange)
plot(histLine, color=color.red, style=plot.style_histogram)

如果您只需要一个值,请使用像这样的占位符'_':

例子

[_, signalLine, _] = ta.macd(close, 12, 26, 9)
plot(signalLine, color=color.orange)

返回值
三个MACD系列的元组:MACD线、信号线和直方图线。

参数

  • source (series int/float) 待执行的系列值。
  • fastlen (simple int) 快线参数
  • slowlen (simple int) 慢长度参数。
  • siglen (simple int) 信号长度参数。

另见
ta.sma ta.ema

ta.mode

返回序列的模式。如果有多个具有相同频率的值,则返回最小值。

ta.mode(source, length)

返回值
序列的模式。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

ta.median

返回序列的中位数。

ta.median(source, length) 

返回值
序列的中位数。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

ta.linreg

线性回归曲线。一条最符合用户定义时间段内指定价格的线。它是使用最小二乘法计算的。此函数的结果使用以下公式计算:linreg = intercept + slope * (length - 1 - offset),其中 intercept 和 slope 是使用 source 系列的最小二乘法计算的值。

ta.linreg(source, length, offset) 

返回值
线性回归曲线

参数

  • source (series int/float) 源系列。
  • length (series int)
  • offset (simple int) 偏移

ta.bb

布林带。布林带是一种技术分析工具,由一组线定义,这些线与证券价格的简单移动平均线(SMA)相距两个标准偏差(正向和负向),但可以根据用户偏好进行调整。

ta.bb(series, length, mult) 

例子

[middle, upper, lower] = ta.bb(close, 5, 4)
plot(middle, color=color.yellow)
plot(upper, color=color.yellow)
plot(lower, color=color.yellow)

// the same on pine
f_bb(src, length, mult) =>
    float basis = ta.sma(src, length)
    float dev = mult * ta.stdev(src, length)
    [basis, basis + dev, basis - dev]

[pineMiddle, pineUpper, pineLower] = f_bb(close, 5, 4)

plot(pineMiddle)
plot(pineUpper)
plot(pineLower)

返回值
布林带。

参数

  • series (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).
  • mult (simple int/float) 标准差因子。

另见
ta.sma ta.stdev ta.kc

ta.bbw

布林带的宽度。布林带宽度是上轨和下轨到中线的距离。

ta.bbw(series, length, mult) 

例子

plot(ta.bbw(close, 5, 4), color=color.yellow)

// the same on pine
f_bbw(src, length, mult) =>
    float basis = ta.sma(src, length)
    float dev = mult * ta.stdev(src, length)
    ((basis + dev) - (basis - dev)) / basis

plot(f_bbw(close, 5, 4))

返回值
布林带宽度。

参数

  • series (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).
  • mult (simple int/float) 标准差因子。

另见
ta.bb ta.sma ta.stdev

ta.cci

CCI(商品路径指数)的计算方法是商品的典型价格与其简单移动平均线之间的差值除以典型价格的平均绝对偏差。该指数按0.015的倒数进行缩放,以提供更多可读的数字。

ta.cci(source, length) 

返回值
lengthK线返回的source的商品渠道指数。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

ta.change

当前值与前一个值之间的差分,source - source[length]。

ta.change(source, length) 
ta.change(source) 

返回值
减法的结果。

参数

  • source (series int/float) 源系列。
  • length (series int) 从当前k线偏移到上一个k线。 可选,如未给予,则使用length = 1。

另见
ta.mom ta.cross

ta.mom

source价格和source价格lengthK线之前的动量。这只是一个差分:source - source[length]。

ta.mom(source, length) 

返回值
source价格和source价格lengthK线之前的动量。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) 从当前k线偏移到上一个k线。

另见
ta.change

ta.cmo

钱德动量摆动指标。计算最近的上涨点数之和与最近的下跌点数之和,然后将两者相减,然后将结果除以同一时期内所有价格变动的总和

ta.cmo(series, length) 

例子

plot(ta.cmo(close, 5), color=color.yellow)

// the same on pine
f_cmo(src, length) =>
    float mom = ta.change(src)
    float sm1 = math.sum((mom >= 0) ? mom : 0.0, length)
    float sm2 = math.sum((mom >= 0) ? 0.0 : -mom, length)
    100 * (sm1 - sm2) / (sm1 + sm2)

plot(f_cmo(close, 5))

返回值
钱德动量摆动指标

参数

  • series (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

另见
ta.rsi ta.stoch math.sum

ta.percentile_linear_interpolation

使用最近的两个排名之间的线性插值方法计算百分比。

ta.percentile_linear_interpolation(source, length, percentage) 

返回值
lengthK线返回的source系列的第P个百分位数。

参数

  • source (series int/float) 待执行的系列值(来源)。
  • length (series int) 过去的K线数量(长度)
  • percentage (simple int/float) 百分比,从0到100的范围内的数字

备注
请注意,使用此方法计算的百分比并非都是输入数据集一员。

另见
ta.percentile_nearest_rank

ta.percentile_nearest_rank

根据最近的排名方法计算百分比。

ta.percentile_nearest_rank(source, length, percentage) 

返回值
lengthK线返回的source系列的第P个百分位数。

参数

  • source (series int/float) 待执行的系列值(来源)。
  • length (series int) 过去的K线数量(长度)
  • percentage (simple int/float) 百分比,从0到100的范围内的数字

备注
使用少于过去100 k线长度的最近排名法可导致相同的数字用于多个百分位数。
最近排名法计算的百分比都是输入数据集一员。
第100个百分点被定义为输入数据集中的最大值。

另见
ta.percentile_linear_interpolation

ta.percentrank

百分比等级是以前的值小于或等于给定系列当前值的百分比。

ta.percentrank(source, length) 

返回值
lengthK线返回的source百分比排名。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

ta.variance

方差是一系列与其均值的平方偏差的期望值 (ta.sma),它非正式地衡量一组数字与其均值的距离。

ta.variance(source, length, biased) 

返回值
length K线返回的source的方差。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).
  • biased (series bool) 确定应该使用哪个估计。可选。默认值为true。

备注
如果biased为true,函数将使用对整个总体的有偏估计进行计算,如果为false - 对样本的无偏估计。

另见
ta.dev ta.stdev

ta.tr

ta.tr(handle_na) 

返回值
真实范围。它是math.max(high - low, math.abs(high - close[1]), math.abs(low - close[1]))。

参数

  • handle_na (simple bool) 如何处理 NaN 值。 如果为 true,并且前一天的收盘价为 NaN,则 tr 将被计算为当天的高-低点。否则(如果为false) tr 在这种情况下将返回 NaN。另请注意,ta.atr 使用 ta.tr(true)。

备注
ta.tr(false)ta.tr完全相同。

另见
ta.atr

ta.mfi

资金流量指标。资金流量指标是一种技术指标,它使用价格和成交量来确定资产中的超买或超卖状况。

ta.mfi(series, length) 

例子

plot(ta.mfi(hlc3, 14), color=color.yellow)

// the same on pine
pine_mfi(src, length) =>
    float upper = math.sum(volume * (ta.change(src) <= 0.0 ? 0.0 : src), length)
    float lower = math.sum(volume * (ta.change(src) >= 0.0 ? 0.0 : src), length)
    mfi = 100.0 - (100.0 / (1.0 + upper / lower))
    mfi

plot(pine_mfi(hlc3, 14))

返回值
资金流量指标

参数

  • series (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

另见
ta.rsi math.sum

ta.kc

肯特纳通道。肯特那通道是一个技术指标,包含了中间的移动平均线以及上下轨的通道。

ta.kc(series, length, mult) 
ta.kc(series, length, mult, useTrueRange) 

例子

[middle, upper, lower] = ta.kc(close, 5, 4)
plot(middle, color=color.yellow)
plot(upper, color=color.yellow)
plot(lower, color=color.yellow)


// the same on pine
f_kc(src, length, mult, useTrueRange) =>
    float basis = ta.ema(src, length)
    float span = (useTrueRange) ? ta.tr : (high - low)
    float rangeEma = ta.ema(span, length)
    [basis, basis + rangeEma * mult, basis - rangeEma * mult]
    
[pineMiddle, pineUpper, pineLower] = f_kc(close, 5, 4, true)

plot(pineMiddle)
plot(pineUpper)
plot(pineLower)

返回值
肯特纳通道

参数

  • series (series int/float) 待执行的系列值。
  • length (simple int) K线数量(长度).
  • mult (simple int/float) 标准差因子。
  • useTrueRange (simple bool) 可选参数。指定是否使用真实范围; 默认为true。 如果值为false,则将使用表达式(high-low)来计算范围。

另见
ta.ema ta.atr ta.bb

ta.kcw

肯特纳通道宽度。肯特那通道宽度是上,下通道之间的差除以中间通道的值。

ta.kcw(series, length, mult) 
ta.kcw(series, length, mult, useTrueRange) 

例子

plot(ta.kcw(close, 5, 4), color=color.yellow)

// the same on pine
f_kcw(src, length, mult, useTrueRange) =>
    float basis = ta.ema(src, length)
    float span = (useTrueRange) ? ta.tr : (high - low)
    float rangeEma = ta.ema(span, length)
    
    ((basis + rangeEma * mult) - (basis - rangeEma * mult)) / basis

plot(f_kcw(close, 5, 4, true))

返回值
肯特纳通道宽度。

参数

  • series (series int/float) 待执行的系列值。
  • length (simple int) K线数量(长度).
  • mult (simple int/float) 标准差因子。
  • useTrueRange (simple bool) 可选参数。指定是否使用真实范围; 默认为true。 如果值为false,则将使用表达式(high-low)来计算范围。

另见
ta.kc ta.ema ta.atr ta.bb

ta.correlation

相关系数。描述两个系列倾向于偏离其ta.sma值的程度。

ta.correlation(source1, source2, length) 

返回值
相关系数。

参数

  • source1 (series int/float) 源系列。
  • source2 (series int/float) 目标系列。
  • length (series int) 长度(K线数量)

另见
request.security

ta.cross

ta.cross(source1, source2) 

返回值
如果两个系列相互交叉则为true,否则为false。

参数

  • source1 (series int/float) 第一数据系列。
  • source2 (series int/float) 第二数据系列。

另见
ta.change

ta.crossover

source1-series被定义为跨越source2-series,如果在当前K线上,source1的值大于source2的值,并且在前一个K线上,source2的值source1小于source2`的值。

ta.crossover(source1, source2) 

返回值
如果source1穿过source2则为true,否则为false。

参数

  • source1 (series int/float) 第一数据系列。
  • source2 (series int/float) 第二数据系列。

ta.crossunder

source1-series 被定义为在 source2-series 下交叉,如果在当前K线上,source1的值小于source2的值,并且在前一根K线上,source1的值大于source2的值。

ta.crossunder(source1, source2) 

返回值
如果source1source2下交叉,则为true,否则为false。

参数

  • source1 (series int/float) 第一数据系列。
  • source2 (series int/float) 第二数据系列。

ta.atr

函数ATR(真实波动幅度均值)返回真实范围的RMA。真实波动幅度是max(high - low, abs(high - close[1]), abs(low - close[1]))。

ta.atr(length) 

例子

plot(ta.atr(14))

//the same on pine
pine_atr(length) =>
    trueRange = na(high[1])? high-low : math.max(math.max(high - low, math.abs(high - close[1])), math.abs(low - close[1]))
    //true range can be also calculated with ta.tr(true)
    ta.rma(trueRange, length)

plot(pine_atr(14))

返回值
真实波动幅度均值(ATR)

参数
length (simple int) 长度(K线数量)

另见
ta.tr ta.rma

ta.sar

抛物线转向(抛物线停止和反向)是J. Welles Wilder, Jr.设计的方法,以找出交易市场价格方向的潜在逆转。

ta.sar(start, inc, max) 

例子

plot(ta.sar(0.02, 0.02, 0.2), style=plot.style_cross, linewidth=3)

// The same on Pine
pine_sar(start, inc, max) =>
	var float result = na
	var float maxMin = na
	var float acceleration = na
	var bool isBelow = na
	bool isFirstTrendBar = false
	
	if bar_index == 1
		if close > close[1]
			isBelow := true
			maxMin := high
			result := low[1]
		else
			isBelow := false
			maxMin := low
			result := high[1]
		isFirstTrendBar := true
		acceleration := start
	
	result := result + acceleration * (maxMin - result)
	
	if isBelow
		if result > low
			isFirstTrendBar := true
			isBelow := false
			result := math.max(high, maxMin)
			maxMin := low
			acceleration := start
	else
		if result < high
			isFirstTrendBar := true
			isBelow := true
			result := math.min(low, maxMin)
			maxMin := high
			acceleration := start
			
	if not isFirstTrendBar
		if isBelow
			if high > maxMin
				maxMin := high
				acceleration := math.min(acceleration + inc, max)
		else
			if low < maxMin
				maxMin := low
				acceleration := math.min(acceleration + inc, max)
	
	if isBelow
		result := math.min(result, low[1])
		if bar_index > 1
			result := math.min(result, low[2])
		
	else
		result := math.max(result, high[1])
		if bar_index > 1
			result := math.max(result, high[2])
	
	result
	
plot(pine_sar(0.02, 0.02, 0.2), style=plot.style_cross, linewidth=3)

返回值
抛物线转向指标。

参数

  • start (simple int/float) 开始。
  • inc (simple int/float) 增加
  • max (simple int/float) 最大.

ta.barssince

从上次条件为true起,计算K线数量。

ta.barssince(condition) 

例子

// get number of bars since last color.green bar
plot(ta.barssince(close >= open))

返回值
如状况为true的k线数目。

备注
如果在当前K线之前从未满足该条件,则该函数返回na。
请注意,使用此变量/函数可能会导致指标重新绘制。

另见
ta.lowestbars ta.highestbars ta.valuewhen ta.highest ta.lowest

ta.cum

source 的累积(全部的)总和。换句话说,它是source的所有元素的总和。

ta.cum(source) 

返回值
系列总和。

参数

  • source (series int/float)

另见
math.sum

ta.dmi

dmi函数返回动向指数DMI。

ta.dmi(diLength, adxSmoothing) 

例子

len = input.int(17, minval=1, title="DI Length")
lensig = input.int(14, title="ADX Smoothing", minval=1, maxval=50)
[diplus, diminus, adx] = ta.dmi(len, lensig)
plot(adx, color=color.red, title="ADX")
plot(diplus, color=color.blue, title="+DI")
plot(diminus, color=color.orange, title="-DI")

返回值
三个DMI系列的元组:正方向运动(+DI)、负方向运动(-DI) 和平均方向运动指数(ADX)。

参数

  • diLength (simple int) DI Period。
  • adxSmoothing (simple int) ADX平滑周期

另见
ta.rsi ta.tsi ta.mfi

ta.falling

测试 source 系列对于 length K线long是否正在下跌。

ta.falling(source, length) 

返回值
如果当前 source 值小于 length K线返回的任何先前 source 值,则为true,否则为false。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

另见
ta.rising

ta.rising

测试 source 系列对于 length K线long是否正在上涨。

ta.rising(source, length) 

返回值
如果当前 source 值大于 length K线返回的任何先前 source 值,则为true,否则为false。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

另见
ta.falling

ta.pivothigh

此函数返回枢轴高点的价格。 如果没有枢轴高点,则返回“NaN”。

ta.pivothigh(source, leftbars, rightbars) 
ta.pivothigh(leftbars, rightbars) 

例子

leftBars = input(2)
rightBars=input(2)
ph = ta.pivothigh(leftBars, rightBars)
plot(ph, style=plot.style_cross, linewidth=3, color= color.red, offset=-rightBars)

返回值
此点的价格或者 'NaN'.

参数

  • source (series int/float) 可选参数。数据序列计算值。预设值'High'。
  • leftbars (series int/float) 左力量。
  • rightbars (series int/float) 右长度。

备注
如果参数'leftbars'或'rightbars'是系列,你应该使用max_bars_back函数作为'source'变量。

ta.pivotlow

此函数返回枢轴低点的价格。 如果没有枢轴低点,它返回“NaN”。

ta.pivotlow(source, leftbars, rightbars) 
ta.pivotlow(leftbars, rightbars) 

例子

leftBars = input(2)
rightBars=input(2)
pl = ta.pivotlow(close, leftBars, rightBars)
plot(pl, style=plot.style_cross, linewidth=3, color= color.blue, offset=-rightBars)

返回值
此点的价格或者 'NaN'.

参数

  • source (series int/float) 可选参数。 数据系列计算值。 默认为“Low”。
  • leftbars (series int/float) 左力量。
  • rightbars (series int/float) 右长度。

备注
如果参数'leftbars'或'rightbars'是系列,你应该使用max_bars_back函数作为'source'变量。

ta.highest

过去k线的给定数目的最高值。

ta.highest(source, length) 
ta.highest(length) 

返回值
系列中的最高值。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

备注
两个 args 版本:source 是一个系列,length 是返回的K线数。
一个 arg 版本:length 是返回的K线数。算法使用high作为 source 系列。

另见
ta.lowest ta.lowestbars ta.highestbars ta.valuewhen ta.barssince

ta.highestbars

过去k线的给定数目的最高值偏移。

ta.highestbars(source, length) 
ta.highestbars(length) 

返回值
偏移到最高k线。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

备注
两个 args 版本:source 是一个系列,length 是返回的K线数。
一个 arg 版本:length 是返回的K线数。算法使用high作为 source 系列。

另见
ta.lowest ta.highest ta.lowestbars ta.barssince ta.valuewhen

ta.stoch

随机指标。计算方程:100 * (close - lowest(low, length)) / (highest(high, length) - lowest(low, length))。

ta.stoch(source, high, low, length) 

返回值
随机

参数

  • source (series int/float) 源系列。
  • high (series int/float) 高系列
  • low (series int/float) 低系列
  • length (series int) 长度(K线数量)

另见
ta.cog

ta.supertrend

超级趋势指标。超级趋势指标是一个跟随趋势的指标。

ta.supertrend(factor, atrPeriod) 

例子

[supertrend, direction] = ta.supertrend(3, 10)
plot(direction < 0 ? supertrend : na, "Up direction", color = color.green, style=plot.style_linebr)
plot(direction > 0 ? supertrend : na, "Down direction", color = color.red, style=plot.style_linebr)

// The same on Pine
pine_supertrend(factor, atrPeriod) =>
	src = hl2
	atr = ta.atr(atrPeriod)
	upperBand = src + factor * atr
	lowerBand = src - factor * atr
	prevLowerBand = nz(lowerBand[1])
	prevUpperBand = nz(upperBand[1])

	lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ? lowerBand : prevLowerBand
	upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ? upperBand : prevUpperBand
	int direction = na
	float superTrend = na
	prevSuperTrend = superTrend[1]
	if na(atr[1])
		direction := 1
	else if prevSuperTrend == prevUpperBand
		direction := close > upperBand ? -1 : 1
	else
		direction := close < lowerBand ? 1 : -1
	superTrend := direction == -1 ? lowerBand : upperBand
	[superTrend, direction]

[pineSupertrend, pineDirection] = pine_supertrend(3, 10)
plot(pineDirection < 0 ? pineSupertrend : na, "Up direction", color = color.green, style=plot.style_linebr)
plot(pineDirection > 0 ? pineSupertrend : na, "Down direction", color = color.red, style=plot.style_linebr)

返回值
两个超趋势系列的元组:超趋势线和趋势方向。可能的值为 1(向上方向)和 -1(向下方向)。

参数

  • factor (series int/float) ATR将乘以的乘数。
  • atrPeriod (simple int) 平均真实波幅长度。

另见
ta.macd

ta.lowest

过去k线的给定数目的最低值。

ta.lowest(source, length) 
ta.lowest(length) 

返回值
系列中的最低值。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

备注
两个 args 版本:source 是一个系列,length 是返回的K线数。
一个 arg 版本:length 是返回的K线数。算法使用low作为source系列。

另见
ta.highest ta.lowestbars ta.highestbars ta.valuewhen ta.barssince

ta.lowestbars

过去k线的给定数目的最低值偏移。

ta.lowestbars(source, length) 
ta.lowestbars(length) 

返回值
偏移到最低k线。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) 返回K线数。

备注
两个 args 版本:source 是一个系列,length 是返回的K线数。
一个 arg 版本:length 是返回的K线数。算法使用low作为source系列。

另见
ta.lowest ta.highest ta.highestbars ta.barssince ta.valuewhen

ta.valuewhen

返回第n次最近出现的“condition”为true的K线的“source”系列值。

ta.valuewhen(condition, source, occurrence) 

例子

slow = ta.sma(close, 7)
fast = ta.sma(close, 14)
// Get value of `close` on second most recent cross
plot(ta.valuewhen(ta.cross(slow, fast), close, 1))

参数

  • condition (series bool) 要搜索的条件。
  • source (series int/float/bool/color) 要从满足条件的K线返回的值。
  • occurrence (simple int) 条件的出现。编号从0开始并按时间回溯,因此“0”是最近出现的“condition”,“1”是第二个最近出现的,依此类推。必须是整数 >= 0。

备注
此功能需要在每根K线上执行。不建议在for或while循环结构中使用它,因为它的行为可能出乎意料。请注意,使用此功能可能会导致指标重绘。

另见
ta.lowestbars ta.highestbars ta.barssince ta.highest ta.lowest

ta.vwap

成交量加权平均价格

ta.vwap(source) 

返回值
成交量加权平均

参数

  • source (series int/float) 源系列。

另见
ta.vwap

ta.vwma

vwma 函数返回 length K线的 source 的成交量加权移动平均值。等同于:sma(source * volume, length) / sma(volume, length)。

ta.vwma(source, length) 

例子

plot(ta.vwma(close, 15))

// same on pine, but less efficient
pine_vwma(x, y) =>
    ta.sma(x * volume, y) / ta.sma(volume, y)
plot(pine_vwma(close, 15))

返回值
lengthK线返回的source的成交量加权移动平均线。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

另见
ta.sma ta.ema ta.rma ta.wma ta.swma ta.alma

ta.wpr

威廉姆斯指标Williams %R。。该振荡指标显示当前收盘价与过去“一段时间内”的高/低价之间的关系。

ta.wpr(length) 

例子

plot(ta.wpr(14), title="%R", color=color.new(#ff6d00, 0))

返回值
Williams %R。

参数

  • length (series int) K线数量。

另见
ta.mfi ta.cmo

plot

plot

在图表上绘制一系列数据。

plot(series, title, color, linewidth, style, trackprice, histbase, offset, join, editable, show_last, display) 

例子

plot(high+low, title='Title', color=color.new(#00ffaa, 70), linewidth=2, style=plot.style_area, offset=15, trackprice=true)

// You may fill the background between any two plots with a fill() function:
p1 = plot(open)
p2 = plot(close)
fill(p1, p2, color=color.new(color.green, 90))

返回值
可用于fill的绘图对象。

参数

  • series (series int/float) 要绘制的数据系列。 必要参数。
  • title (const string) 绘图标题。
  • color (series color) 绘图的颜色。您可以使用如'color = red'或'color =#ff001a'的常量以及如 'color = close >= open ? green : red'的复杂表达式。 可选参数。
  • linewidth (input int) 绘制线的宽度。默认值为1。不适用于每种样式。
  • style (plot_style) plot类型。可能的值有:plot.style_line、plot.style_stepline、plot.style_stepline_diamond、plot.style_histogram、plot.style_cross、plot.style_area、plot.style_columns、plot.style_circles、plot.style_linebr、plot.style_areabr。默认值为plot.style_line。
  • trackprice (input bool) 如果为true,则水平价格线将显示在最后一个指标值的水平。默认为false。
  • histbase (input int/float) 以plot.style_histogram,plot.style_columns或plot.style_area样式绘制图时,用作参考水平的价格值。默认值为0.0。
  • offset (series int) 在k线特定数量上向左或向右移动绘图。 默认值为0。
  • join (input bool) 如果为true,则绘图点将与线连接,仅适用于plot.style_cross和plot.style_circles样式。 默认值为false。
  • editable (const bool) 如果为true,则绘图样式可在格式对话框中编辑。 默认值为true。
  • show_last (input int) 如已设置,则定义在图表上绘制的k线数(从最后k线返回过去)。
  • display (plot_display) 控制显示绘图的位置。可能的值为:display.none、display.all。预设值为display.all。
  • overlay (const bool) FMZ平台扩展的参数,用于设置当前函数在主图(设置true)或者副图(设置false)上画图显示,默认值为false。不指定该参数则按照strategy或者indicator中的overlay参数设置,strategy或者indicator没有设置overlay参数,则按照默认参数处理。

另见
plotshape plotchar bgcolor

plotshape

在图表上绘制可视形状。

plotshape(series, title, style, location, color, offset, text, textcolor, editable, size, show_last, display) 

例子

data = close >= open
plotshape(data, style=shape.xcross)

参数

  • series (series bool) 作为形状绘制的一系列数据 。 除了location.absolute之外,系列被视为所有位置值的一系列布尔值。 必要参数。
  • title (const string) 绘图标题。
  • style (input string) 绘图类型。可能的值有:shape.xcross,shape.cross,shape.triangleup,shape.triangledown,shape.flag,shape.circle,shape.arrowup,shape.arrowdown,shape.labelup,shape.labeldown,shape.square,shape.diamond。 默认值为shape.xcross。
  • location (input string) 形状在图表上的位置。 可能的值有:location.abovebar,location.belowbar,location.top,location.bottom,location.absolute。 默认值为location.abovebar。
  • color (series color) 形状的颜色。 您可以使用如'color = red'或'color =#ff001a'的常量以及如 'color = close >= open ? green : red'的复杂表达式。 可选参数。
  • offset (series int) 在k线特定数量上向左或向右移动形状。 默认值为0。
  • text (const string) 文字以形状显示。 您可以使用多行文本,分隔行使用'\n'转义序列。示例:'line one\nline two'。
  • textcolor (series color) 文字的颜色。 您可以使用如 'textcolor=red' 或'textcolor=#ff001a' 的常量,以及如'textcolor = close >= open ? green : red'的复杂表达式。 可选参数。
  • editable (const bool) 如果为true,则plotshape样式可在格式对话框中编辑。 默认值为true。
  • show_last (input int) 如已设置,则定义在图表上绘制的形状数(从最后k线返回过去)。
  • size (const string) 图表上字符的大小。 可能的值有: size.auto, size.tiny, size.small, size.normal, size.large, size.huge。默认值为size.auto。
  • display (plot_display) 控制显示绘图的位置。可能的值为:display.none、display.all。预设值为display.all。
  • overlay (const bool) FMZ平台扩展的参数,用于设置当前函数在主图(设置true)或者副图(设置false)上画图显示,默认值为false。不指定该参数则按照strategy或者indicator中的overlay参数设置,strategy或者indicator没有设置overlay参数,则按照默认参数处理。

另见
plot plotchar bgcolor

plotchar

在图表上使用任何给定的Unicode字符绘制可视形状。

plotchar(series, title, char, location, color, offset, text, textcolor, editable, size, show_last, display) 

例子

data = close >= open
plotchar(data, char='❄')

参数

  • series (series bool) 作为形状绘制的一系列数据 。 除了location.absolute之外,系列被视为所有位置值的一系列布尔值。 必要参数。
  • title (const string) 绘图标题。
  • char (input string) 作为视觉形状使用的字符
  • location (input string) 形状在图表上的位置。 可能的值有:location.abovebar,location.belowbar,location.top,location.bottom,location.absolute。 默认值为location.abovebar。
  • color (series color) 形状的颜色。 您可以使用如'color = red'或'color =#ff001a'的常量以及如 'color = close >= open ? green : red'的复杂表达式。 可选参数。
  • offset (series int) 在k线特定数量上向左或向右移动形状。 默认值为0。
  • text (const string) 文字以形状显示。 您可以使用多行文本,分隔行使用'\n'转义序列。示例:'line one\nline two'。
  • textcolor (series color) 文字的颜色。 您可以使用如 'textcolor=red' 或'textcolor=#ff001a' 的常量,以及如'textcolor = close >= open ? green : red'的复杂表达式。 可选参数。
  • editable (const bool) 如果为true,则plotchar样式可在格式对话框中编辑。 默认值为true。
  • show_last (input int) 如已设置,则定义在图表上绘制的图表数(从最后k线返回过去)。
  • size (const string) 图表上字符的大小。 可能值有:size.auto,size.tiny,size.small,size.normal,size.large,size.huge。 默认值为size.auto。
  • display (plot_display) 控制显示绘图的位置。可能的值为:display.none、display.all。预设值为display.all。
  • overlay (const bool) FMZ平台扩展的参数,用于设置当前函数在主图(设置true)或者副图(设置false)上画图显示,默认值为false。不指定该参数则按照strategy或者indicator中的overlay参数设置,strategy或者indicator没有设置overlay参数,则按照默认参数处理。

另见
plot plotshape bgcolor

plotcandle

在图表上绘制蜡烛。

plotcandle(open, high, low, close, title, color, wickcolor, editable, show_last, bordercolor, display)

例子

indicator("plotcandle example", overlay=true)
plotcandle(open, high, low, close, title='Title', color = open < close ? color.green : color.red, wickcolor=color.black)

参数

  • open (series int/float) 数据开放系列用作蜡烛开放值。必要参数。
  • high (series int/float) 高系列数据用作蜡烛的高值。必要参数。
  • low (series int/float) 低系列数据被用作蜡烛的低值。 必要参数。
  • close (series int/float) 关闭系列数据作为关闭k线的值。 必要参数。
  • title (const string) plotcandle的标题。 可选参数。
  • color (series color) 蜡烛的颜色。您可以使用如'color = red'或'color =#ff001a'的常量以及像'color = close >= open ? green : red'的复杂表达式。可选参数。
  • wickcolor (series color) 蜡烛灯芯的颜色。一个可选参数。
  • editable (const bool) 如果为true,则plotcandle样式可在格式对话框中编辑。 默认值为true。
  • show_last (input int) 如已设置,则定义在图表上绘制的蜡烛数(从最后k线返回过去)。
  • bordercolor (series color) 蜡烛的边框颜色。一个可选参数。
  • display (plot_display) 控制显示绘图的位置。可能的值为:display.none、display.all。预设值为display.all。
  • overlay (const bool) FMZ平台扩展的参数,用于设置当前函数在主图(设置true)或者副图(设置false)上画图显示,默认值为false。不指定该参数则按照strategy或者indicator中的overlay参数设置,strategy或者indicator没有设置overlay参数,则按照默认参数处理。

备注
如果开高低收都是NaN,那么K线不需要显示出来。
开、高、低、收的最大值将被设置为“高”,最小值被设置为“低”。

另见
plotbar

plotarrow

在图表上绘制向上和向下箭头:向上箭头绘制在每个正值指示器上,而向下箭头绘制在每个负值上。 如果指标返回na,则不会绘制箭头。 箭头具有不同的高度,指标的绝对值越大,绘制箭头越长。

plotarrow(series, title, colorup, colordown, offset, minheight, maxheight, editable, show_last, display)

例子

codiff = close - open
plotarrow(codiff, colorup=color.new(color.teal,40), colordown=color.new(color.orange, 40), overlay=true)

参数

  • series (series int/float) 要绘制成箭头的数据系列。 必要参数。
  • title (const string) 绘图标题。
  • colorup (series color) 向上箭头的颜色。可选参数。
  • colordown (series color) 向下箭头的颜色。可选参数。
  • offset (series int) 在K线特定数量上向左或向右移动箭头。 默认值为0。
  • minheight (input int) 以像素为单位最小可能的箭头高度。默认值为5。
  • maxheight (input int) 以像素为单位的最大可能的箭头高度。默认值为100
  • editable (const bool) 如果为true,则plotarrow样式可在格式对话框中编辑。 默认值为true。
  • show_last (input int) 如已设置,则定义在图表上绘制的箭数(从最后k线返回过去)。
  • display (plot_display) 控制显示绘图的位置。可能的值为:display.none、display.all。预设值为display.all。
  • overlay (const bool) FMZ平台扩展的参数,用于设置当前函数在主图(设置true)或者副图(设置false)上画图显示,默认值为false。不指定该参数则按照strategy或者indicator中的overlay参数设置,strategy或者indicator没有设置overlay参数,则按照默认参数处理。

另见
plot plotshape plotchar barcolor bgcolor

array

array.pop

该函数从阵列中删除最后一个元素并返回其值。

array.pop(id)

例子

// array.pop example
a = array.new_float(5,high)
removedEl = array.pop(a)
plot(array.size(a))
plot(removedEl)

返回值
被删除元素的值。

参数

  • id (any array type) 阵列对象。

另见
array.new_float array.set array.push array.remove array.insert array.shift

array.shift

该函数删除阵列的第一个元素并返回其值。

array.shift(id)

例子

// array.shift example
a = array.new_float(5,high)
removedEl = array.shift(a)
plot(array.size(a))
plot(removedEl)

返回值
被删除元素的值。

参数

  • id (any array type) 阵列对象。

另见
array.unshift array.set array.push array.remove array.includes

array.unshift

该函数将值插入阵列的初始位置。

array.unshift(id, value)

例子

// array.unshift example
a = array.new_float(5, 0)
array.unshift(a, open)
plot(array.get(a, 0))

参数

  • id (any array type) 阵列对象。
  • value (series <type of the array's elements>) 要添加到阵列初始位置的值。

另见
array.shift array.set array.insert array.remove array.indexof

array.size

该函数返回阵列中元素的数量。

array.size(id)

例子

// array.size example
a = array.new_float(0)
for i = 0 to 9
    array.push(a, close[i])
// note that changes in slice also modify original array
slice = array.slice(a, 0, 5)
array.push(slice, open)
// size was changed in slice and in original array
plot(array.size(a))
plot(array.size(slice))

返回值
阵列中元素的数量。

参数

  • id (any array type) 阵列对象。

另见
array.new_float array.sum array.slice array.sort

array.slice

该函数从现有阵列创建分片。如果分片中的对象发生更改,则更改将同时应用于新阵列和原始阵列。

array.slice(id, index_from, index_to)

例子

// array.slice example
a = array.new_float(0)
for i = 0 to 9
    array.push(a, close[i])
// take elements from 0 to 4
// *note that changes in slice also modify original array 
slice = array.slice(a, 0, 5)
plot(array.sum(a) / 10)
plot(array.sum(slice) / 5)

返回值
阵列分片的浅拷贝。

参数

  • id (any array type) 阵列对象。
  • index_from (series int) 从零开始的索引以开始提取。
  • index_to (series int) 从零开始的索引在完成提取之前。该函数提取此索引之前的元素。

另见
array.new_float array.get array.sort

array.abs

返回一个阵列,其中包含原始阵列中每个元素的绝对值。

array.abs(id)

参数

  • id (int[]/float[]) 阵列对象。

另见
array.new_float array.insert array.slice array.reverse order.ascending order.descending

array.binary_search

该函数返回值的索引,如果未找到该值,则返回-1。要搜索的阵列必须按升序排序。

array.binary_search(id, val)

例子

// array.binary_search
a = array.from(5, -2, 0, 9, 1)
array.sort(a) // [-2, 0, 1, 5, 9]
position = array.binary_search(a, 0) // 1
plot(position)

参数

  • id (int[]/float[]) 阵列对象。
  • val (series int/float) 在阵列中搜索的值。

备注
二进制搜索适用于按升序预先排序的阵列。它首先将阵列中间的元素与目标值进行比较。如果元素与目标值匹配,则返回其在阵列中的位置。如果元素的值大于目标值,则在阵列的下半部分继续搜索。如果元素的值小于目标值,则在阵列的上半部分继续搜索。通过递归地执行此操作,该算法逐渐消除了阵列中目标值不能位于的越来越小的部分。

另见
array.new_float array.insert array.slice array.reverse order.ascending order.descending

array.binary_search_leftmost

如果找到值,该函数将返回该值的索引。当未找到值时,该函数返回下一个最小元素的索引,如果它在阵列中,则在值所在位置的左侧。要搜索的阵列必须按升序排序。

array.binary_search_leftmost(id, val)

例子

// array.binary_search_leftmost
a = array.from(5, -2, 0, 9, 1)
array.sort(a) // [-2, 0, 1, 5, 9]
position = array.binary_search_leftmost(a, 3) // 2
plot(position)

参数

  • id (int[]/float[]) 阵列对象。
  • val (series int/float) 在阵列中搜索的值。

备注
二进制搜索适用于按升序预先排序的阵列。它首先将阵列中间的元素与目标值进行比较。如果元素与目标值匹配,则返回其在阵列中的位置。如果元素的值大于目标值,则在阵列的下半部分继续搜索。如果元素的值小于目标值,则在阵列的上半部分继续搜索。通过递归地执行此操作,该算法逐渐消除了阵列中目标值不能位于的越来越小的部分。

另见
array.new_float array.insert array.slice array.reverse order.ascending order.descending

array.binary_search_rightmost

如果找到该值,该函数将返回该值的索引。当未找到该值时,该函数返回该值在阵列中所在位置右侧的元素的索引。阵列必须按升序排序。

array.binary_search_rightmost(id, val)

例子

// array.binary_search_rightmost
a = array.from(5, -2, 0, 9, 1)
array.sort(a) // [-2, 0, 1, 5, 9]
position = array.binary_search_rightmost(a, 3) // 3
plot(position)

参数

  • id (int[]/float[]) 阵列对象。
  • val (series int/float) 在阵列中搜索的值。

备注
二进制搜索按升序对已排序的阵列起作用。它首先将阵列中间的元素与目标值进行比较。如果元素与目标值匹配,则返回其在阵列中的位置。如果元素的值大于目标值,则在阵列的下半部分继续搜索。如果元素的值小于目标值,则在阵列的上半部分继续搜索。通过递归地执行此操作,该算法逐渐消除了阵列中目标值不能位于的越来越小的部分。

另见
array.new_float array.insert array.slice array.reverse order.ascending order.descending

array.sort

该函数对阵列的元素进行排序。

array.sort(id, order)

例子

// array.sort example
a = array.new_float(0,0)
for i = 0 to 5
    array.push(a, high[i])
array.sort(a, order.descending)
if barstate.islast
    runtime.log(str.tostring(a))

参数

  • id (int[]/float[]/string[]) 阵列对象。
  • order (sort_order) 排序顺序:order.ascending(默认)或order.descending。

另见
array.new_float array.insert array.slice array.reverse order.ascending order.descending

array.sort_indices

返回一个索引阵列,当用于索引原始阵列时,将按其排序顺序访问其元素。它不会修改原始阵列。

array.sort_indices(id, order)

例子

// array.sort_indices
a = array.from(5, -2, 0, 9, 1)
sortedIndices = array.sort_indices(a) // [1, 2, 4, 0, 3]
indexOfSmallestValue = array.get(sortedIndices, 0) // 1
smallestValue = array.get(a, indexOfSmallestValue) // -2
plot(smallestValue)

参数

  • id (int[]/float[]/string[]) 阵列对象。
  • order (sort_order) 排序顺序:order.ascending 或 order.descending。可选。默认值为 order.ascending。

另见
array.new_float array.insert array.slice array.reverse order.ascending order.descending

array.clear

该函数从阵列中删除所有元素。

array.clear(id)

例子

// array.clear example
a = array.new_float(5,high)
array.clear(a)
array.push(a, close)
plot(array.get(a,0))
plot(array.size(a))

参数

  • id (any array type) 阵列对象。

另见
array.new_float array.insert array.push array.remove array.pop

array.concat

该函数用于合并两个阵列。它将所有元素从第二个阵列推送到第一个阵列,然后返回第一个阵列。

array.concat(id1, id2)

例子

// array.concat example
a = array.new_float(0,0)
b = array.new_float(0,0)
for i = 0 to 4
    array.push(a, high[i])
    array.push(b, low[i])
c = array.concat(a,b)
plot(array.size(a))
plot(array.size(b))
plot(array.size(c))

返回值
第一个阵列具有来自第二个阵列的合并元素。

参数

  • id1 (any array type) 第一个阵列对象。
  • id2 (any array type) 第二个阵列对象。

另见
array.new_float array.insert array.slice

array.copy

该函数创建现有阵列的副本。

array.copy(id)

例子

// array.copy example
length = 5
a = array.new_float(length, close)
b = array.copy(a)
a := array.new_float(length, open)
plot(array.sum(a) / length)
plot(array.sum(b) / length)

返回值
阵列的副本。

参数

  • id (any array type) 阵列对象。

另见
array.new_float array.get array.slice array.sort

array.stdev

该函数返回阵列元素的标准差。

array.stdev(id, biased)

例子

// array.stdev example
a = array.new_float(0)
for i = 0 to 9
    array.push(a, close[i])
plot(array.stdev(a))

返回值
阵列元素的标准差。

参数

  • id (int[]/float[]) 阵列对象。
  • biased (series bool) 确定应该使用哪个估计。可选。默认值为true。

备注
如果biased为true,函数将使用对整个总体的有偏估计进行计算,如果为false - 对样本的无偏估计。

另见
array.new_float array.max array.min array.avg

array.standardize

该函数返回标准化元素的阵列。

array.standardize(id)

例子

// array.standardize example
a = array.new_float(0)
for i = 0 to 9
    array.push(a, close[i])
b = array.standardize(a)
plot(array.min(b))
plot(array.max(b))

返回值
标准化元素的阵列。

参数

  • id (int[]/float[]) 阵列对象。

另见
array.max array.min array.mode array.avg array.variance array.stdev

array.variance

该函数返回阵列元素的方差。

array.variance(id, biased)

例子

// array.variance example
a = array.new_float(0)
for i = 0 to 9
    array.push(a, close[i])
plot(array.variance(a))

返回值
阵列元素的方差。

参数

  • id (int[]/float[]) 阵列对象。
  • biased (series bool) 确定应该使用哪个估计。可选。默认值为true。

备注
如果biased为true,函数将使用对整个总体的有偏估计进行计算,如果为false - 对样本的无偏估计。

另见
array.new_float array.stdev array.min array.avg array.covariance

array.covariance

该函数返回两个阵列的协方差。

array.covariance(id1, id2, biased)

例子

// array.covariance example
a = array.new_float(0)
b = array.new_float(0)
for i = 0 to 9
    array.push(a, close[i])
    array.push(b, open[i])
plot(array.covariance(a, b))

返回值
两个阵列的协方差。

参数

  • id1 (int[]/float[]) 阵列对象。
  • id2 (int[]/float[]) 阵列对象。
  • biased (series bool) 确定应该使用哪个估计。可选。默认值为true。

备注
如果biased为true,函数将使用对整个总体的有偏估计进行计算,如果为false - 对样本的无偏估计。

另见
array.new_float array.max array.stdev array.avg array.variance

array.fill

该函数将阵列的元素设置为单个值。如果未指定索引,则设置所有元素。如果仅提供起始索引(默认为0),则设置从该索引开始的元素。如果同时使用两个索引参数,则会设置从开始索引到但不包括结束索引的元素(默认值为na)。

array.fill(id, value, index_from, index_to)

例子

// array.fill example
a = array.new_float(10)
array.fill(a, close)
plot(array.sum(a))

参数

  • id (any array type) 阵列对象。
  • value (series <type of the array's elements>) 用于填充阵列的值。
  • index_from (series int) 起始索引,默认为0。
  • index_to (series int) 结束索引,默认为na。必须大于要设置的最后一个元素的索引。

另见
array.new_float array.set array.slice

array.includes

如果在阵列中找到该值,则该函数返回true,否则返回false。

array.includes(id, value)

例子

// array.includes example
a = array.new_float(5,high)
p = close
if array.includes(a, high)
    p := open
plot(p)

返回值
如果在阵列中找到该值,则为true,否则为false。

参数

  • id (any array type) 阵列对象。
  • value (series <type of the array's elements>) 要在阵列中搜索的值。

另见
array.new_float array.indexof array.shift array.remove array.insert

array.insert

该函数通过在适当位置添加新元素来更改阵列的内容。

array.insert(id, index, value)

例子

// array.insert example
a = array.new_float(5, close)
array.insert(a, 0, open)
plot(array.get(a, 5))

参数

  • id (any array type) 阵列对象。
  • index (series int) 插入值的索引。
  • value (series <type of the array's elements>) 要添加到阵列的值。

另见
array.new_float array.set array.push array.remove array.pop array.unshift

array.join

该函数通过连接阵列的所有元素来建立并返回新字符串,用指定的分隔符字符串分隔。

array.join(id, separator)

例子

// array.join example
a = array.new_float(5, 5)
runtime.log(array.join(a, ","))

参数

  • id (int[]/float[]/string[]) 阵列对象。
  • separator (series string) 用于分隔每个阵列元素的字符串。

另见
array.new_float array.set array.insert array.remove array.pop array.unshift

array.lastindexof

此函数返回值最后一次出现的索引。如果找不到该值,则返回 -1。

array.lastindexof(id, value)

例子

// array.lastindexof example
a = array.new_float(5,high)
index = array.lastindexof(a, high)
plot(index)

返回值
元素的索引。

参数

  • id (any array type) 阵列对象。
  • value (series <type of the array's elements>) 要在阵列中搜索的值。

另见
array.new_float array.set array.push array.remove array.insert

array.max

该函数返回最大值,或给定阵列中的第n个最大值。

array.max(id, nth)

例子

// array.max
a = array.from(5, -2, 0, 9, 1)
secondHighest = array.max(a, 2) // 1
plot(secondHighest)

返回值
阵列中的最大值或第n个最大值。

参数

  • id (int[]/float[]) 阵列对象。
  • nth (series int) 返回的第n个最大值,其中0是最大值。可选。默认为零。

另见
array.new_float array.min array.sum

array.min

该函数返回最小值,或给定序列中的第n个最小值。

array.min(id, nth)

例子

// array.min
a = array.from(5, -2, 0, 9, 1)
secondLowest = array.min(a, 1) // 0
plot(secondLowest)

返回值
阵列中的最小值或第n个最小值。

参数

  • id (int[]/float[]) 阵列对象。
  • nth (series int) 要返回的第n个最小值,其中0是最小值。可选。默认为零。

另见
array.new_float array.max array.sum

array.median

该函数返回阵列元素的中位数。

array.median(id)

例子

// array.median example
a = array.new_float(0)
for i = 0 to 9
    array.push(a, close[i])
plot(array.median(a))

返回值
阵列元素的中位数。

参数

  • id (int[]/float[]) 阵列对象。

另见
array.avg array.variance array.min

array.mode

该函数返回阵列元素的模式。如果有多个具有相同频率的值,则返回最小值。

array.mode(id)

例子

// array.mode example
a = array.new_float(0)
for i = 0 to 9
    array.push(a, close[i])
plot(array.mode(a))

返回值
阵列元素的模式。

参数

  • id (int[]/float[]) 阵列对象。

另见
array.new_float array.avg array.variance array.min

array.percentile_linear_interpolation

返回数组值的指定百分比(百分位数)小于或等于它的值,使用线性插值。

array.percentile_linear_interpolation(id, percentage) 

参数

  • id (int[]/float[]) 阵列对象。
  • percentage (series int/float) 必须等于或小于返回值的值的百分比。

备注
在统计数据中,百分位是出现在某个分数或低于某个分数的排名项目的百分比。此测量显示低于您测量的百分等级的标准频率分布中的分数百分比。线性插值估计两个排名之间的值。

另见
array.new_float array.insert array.slice array.reverse order.ascending order.descending

array.percentile_nearest_rank

使用最近秩方法返回指定百分比的数组值(百分位数)小于或等于它的值。

array.percentile_nearest_rank(id, percentage) 

参数

  • id (int[]/float[]) 阵列对象。
  • percentage (series int/float) 必须等于或小于返回值的值的百分比。

备注
在统计数据中,百分位是出现在某个分数或低于某个分数的排名项目的百分比。 此测量显示低于您正在测量的百分排名的标准频率分布中的分数百分比。

另见
array.new_float array.insert array.slice array.reverse order.ascending order.descending

array.percentrank

返回阵列中值的百分位排名。

array.percentrank(id, index) 

参数

  • id (int[]/float[]) 阵列对象。
  • index (series int) 计算其百分排名的值。

备注
百分位排名是数组中有多少元素小于或等于参考值的百分比。

另见
array.new_float array.insert array.slice array.reverse order.ascending order.descending

array.range

该函数返回给定数组的最小值和最大值之间的差。

array.range(id) 

例子

// array.range example
a = array.new_float(0)
for i = 0 to 9
    array.push(a, close[i])
plot(array.range(a))

返回值
数组中最小值和最大值之间的差。

参数

  • id (int[]/float[]) 阵列对象。

另见
array.new_float array.min array.max array.sum

array.remove

该函数通过删除具有指定索引的元素来更改阵列的内容。

array.remove(id, index)

例子

// array.remove example
a = array.new_float(5,high)
removedEl = array.remove(a, 0)
plot(array.size(a))
plot(removedEl)

返回值
被删除元素的值。

参数

  • id (any array type) 阵列对象。
  • index (series int) 要删除的元素索引。

另见
array.new_float array.set array.push array.insert array.pop array.shift

array.reverse

此函数反转阵列。第一个阵列元素变成最后一个,最后一个阵列元素变成第一个。

array.reverse(id)

例子

// array.reverse example
a = array.new_float(0)
for i = 0 to 9
    array.push(a, close[i])
plot(array.get(a, 0))
array.reverse(a)
plot(array.get(a, 0))

参数

  • id (any array type) 阵列对象。

另见
array.new_float array.sort array.push array.set array.avg

array.from

该函数采用以下类型之一的可变数量的参数:int、float、bool、string、line、color、linefill,并返回相应类型的阵列。

array.from(arg0, arg1, ...)

例子

// array.from_example
arr = array.from("Hello", "World!") // arr (string[]) will contain 2 elements: {Hello}, {World!}.
plot(close)

返回值
阵列元素的值。

参数

  • arg0, arg1, ... (series int/float/bool/color/string/line/linefill) 数组参数。

array.new

该函数创建一个新的<type>元素数组对象。

array.new(size, initial_value)

例子

// array.new<string> example
a = array.new<string>(1, "Hello, World!")
runtime.log(array.get(a, 0))

例子

// array.new<color> example
a = array.new<color>()
array.push(a, color.red)
array.push(a, color.green)
plot(close, color = array.get(a, close > open ? 1 : 0))

例子

// array.new<float> example
length = 5
var a = array.new<float>(length, close)
if array.size(a) == length
	array.remove(a, 0)
	array.push(a, close)
plot(array.sum(a) / length, "SMA")

例子

// array.new<line> example
// draw last 15 lines
var a = array.new<line>()
array.push(a, line.new(bar_index - 1, close[1], bar_index, close))
if array.size(a) > 15
    ln = array.shift(a)
    line.delete(ln)

返回值
可与其他阵列一起使用的阵列对象的ID。*()函数。

参数

  • size (series int) 序列的初始大小。可选。默认值为0。
  • initial_value (series <type>) 所有序列元素的初始值。可选。默认值为“na”。

备注
阵列索引从0开始。
如果要初始化一个阵列并同时指定其所有元素,请使用函数array.from。

另见
array.from array.push array.get array.size array.remove array.shift array.sum

array.new_bool

此函数创建一个由bool类型的元素组成的新阵列对象。

array.new_bool(size, initial_value)

例子

// array.new_bool example
length = 5
a = array.new_bool(length, close > open)
plot(array.get(a, 0) ? close : open)

返回值
可与其他阵列一起使用的阵列对象的ID。*()函数。

参数

  • size (series int) 序列的初始大小。可选。默认值为0。
  • initial_value (series bool) 所有序列元素的初始值。可选。默认值为“na”。

备注
阵列索引从0开始。

另见
array.new_float array.get array.slice array.sort

array.new_float

此函数创建一个新的浮点型元素阵列对象。

array.new_float(size, initial_value)

例子

// array.new_float example
length = 5
a = array.new_float(length, close)
plot(array.sum(a) / length)

返回值
可与其他阵列一起使用的阵列对象的ID。*()函数。

参数

  • size (series int) 序列的初始大小。可选。默认值为0。
  • initial_value (series int/float) 所有序列元素的初始值。可选。默认值为“na”。

备注
阵列索引从0开始。

另见
array.new_bool array.get array.slice array.sort

array.new_int

该函数创建一个由int类型的元素组成的新阵列对象。

array.new_int(size, initial_value)

例子

// array.new_int example
length = 5
a = array.new_int(length, int(close))
plot(array.sum(a) / length)

返回值
可与其他阵列一起使用的阵列对象的ID。*()函数。

参数

  • size (series int) 序列的初始大小。可选。默认值为0。
  • initial_value (series int) 所有序列元素的初始值。可选。默认值为“na”。

备注
阵列索引从0开始。

另见
array.new_float array.get array.slice array.sort

array.new_string

该函数创建一个字符串类型元素的新阵列对象。

array.new_string(size, initial_value)

例子

// array.new_string example
length = 5
a = array.new_string(length, "text")
runtime.log(array.get(a, 0))

返回值
可与其他阵列一起使用的阵列对象的ID。*()函数。

参数

  • size (series int) 序列的初始大小。可选。默认值为0。
  • initial_value (series string) 所有序列元素的初始值。可选。默认值为“na”。

备注
阵列索引从0开始。

另见
array.new_float array.get array.slice

array.get

该函数返回指定索引处元素的值。

array.get(id, index)

例子

// array.get example
a = array.new_float(0)
for i = 0 to 9
	array.push(a, close[i] - open[i])
plot(array.get(a, 9))

返回值
阵列元素的值。

参数

  • id (any array type) 阵列对象。
  • index (series int) 要返回其值的元素的索引。

另见
array.new_float array.set array.slice array.sort

array.push

该函数将一个值附加到阵列。

array.push(id, value)

例子

// array.push example
a = array.new_float(5, 0)
array.push(a, open)
plot(array.get(a, 5))

参数

  • id (any array type) 阵列对象。
  • value (series <type of the array's elements>) 添加到阵列末尾的元素值。

另见
array.new_float array.set array.insert array.remove array.pop array.unshift

array.set

该函数将元素的值设置为指定的索引。

array.set(id, index, value) 

例子

// array.set example
a = array.new_float(10)
for i = 0 to 9
	array.set(a, i, close[i])
plot(array.sum(a) / 10)

参数

  • id (any array type) 阵列对象。
  • index (series int) 要修改元素的索引。
  • value (series <type of the array's elements>) 要设置的新值。

另见
array.new_float array.get array.slice

array.sum

该函数返回阵列元素的总和。

array.sum(id) 

例子

// array.sum example
a = array.new_float(0)
for i = 0 to 9
	array.push(a, close[i])
plot(array.sum(a))

返回值
阵列元素的总和。

参数

  • id (int[]/float[]) 阵列对象。

另见
array.new_float array.max array.min

array.avg

该函数返回阵列元素的均值。

array.avg(id)

例子

// array.avg example
a = array.new_float(0)
for i = 0 to 9
	array.push(a, close[i])
plot(array.avg(a))

返回值
阵列元素的均值。

参数

  • id (int[]/float[]) 阵列对象。

另见
array.new_float array.max array.min array.stdev

array.indexof

此函数返回值首次出现的索引。如果找不到该值,则返回 -1。

array.indexof(id, value)

例子

// array.indexof example
a = array.new_float(5,high)
index = array.indexof(a, high)
plot(index)

返回值
元素的索引。

参数

  • id (any array type) 阵列对象。
  • value (series <type of the array's elements>) 要在阵列中搜索的值。

另见
array.lastindexof array.get array.lastindexof array.remove array.insert

strategy

strategy相关的内置函数中,止损点数、止盈点数定义为价格一跳的倍数。例如strategy.exit函数的profitloss参数以点表示止损、止盈,参数profit设置为10,即价格一跳乘以10作为止盈价差,价格一跳即内置变量syminfo.mintick

strategy

该函数设置了多个策略属性。
注意,传参仅支持titleshorttitleoverlaypyramidingdefault_qty_typedefault_qty_value参数,其它参数可以通过PINE语言策略的界面参数设置。

strategy(title, shorttitle, overlay, format, precision, scale, pyramiding, calc_on_order_fills, calc_on_every_tick, max_bars_back, backtest_fill_limits_assumption, default_qty_type, default_qty_value, initial_capital, currency, slippage, commission_type, commission_value, process_orders_on_close, close_entries_rule, margin_long, margin_short, explicit_plot_zorder, max_lines_count, max_labels_count, max_boxes_count, risk_free_rate) 

例子

strategy("Strategy", overlay = true)

// Enter long by market if current open is greater than previous high.
strategy.entry("Long", strategy.long, 1, when = open > high[1])
// Generate a full exit bracket (profit 10 points, loss 5 points per contract) from the entry named "Long".
strategy.exit("Exit", "Long", profit = 10, loss = 5)

参数

  • title (const string) 将在指标/策略插件中看到的指标标题。参数是必需的。
  • shorttitle (const string) 将在图表图例中看到的指标短标题。参数是可选的。
  • overlay (const bool) 如果为true,则该指标将被添加为主要系列的叠加层。如果为false - 它将被添加到单独的图表窗格中。默认为false。
  • format (const string) 价格轴上格式化指标值的类型可能的值为:format.inherit、format.price、format.volume。默认为format.inherit。
  • precision (const int) 价格轴上指标值的浮点数后的位数。必须是非负整数且不大于16。如果省略,则使用父系列的格式。如果format为format.inherit并且设置了此参数,则format变为format.price。
  • scale (scale_type) 指标应跟随价格坐标。可能的值为:scale.right,scale.left,scale.none。值scale.none只能只能与'overlay=true'设置结合使用。
  • pyramiding (const int) 同一方向允许的最大数量。如果该值为0,则只能打开同一方向的一个入场订单,任何其他入场订单将被拒绝。默认值为0。
  • calc_on_order_fills (const bool) 额外的intrabar订单计算。如果参数被设置为“true”,那么一旦K线内在订单后填满,策略就会重新计算(不仅仅在关闭k线之时)。默认值为“false”。
  • calc_on_every_tick (const bool) 额外的intrabar策略计算。如果参数为“true”,策略将实时计算每个刻度,而不关闭k线。该参数不影响历史数据的策略计算。默认值为“false”。
  • max_bars_back (const int) 可用于历史参考策略的最大蜡烛数。 如果在脚本代码中引用了变量的历史数据(使用了'[]'运算符),则此参数将应用于脚本中的每个内置变量或用户变量。 Pine脚本中的可变缓冲区大小通常是自动检测的。 然而,在某些情况下这是不可能的,这就是参数允许用户手动设置该值的下限的原因。 注意:使用max_bars_back函数而不是参数是最佳的,因为它仅适用于一个变量。
  • backtest_fill_limits_assumption (const int) 限价单执行假设。只有当市价超过限价单水平指定的tick数时,限价单才会在intrabar成交。
  • default_qty_type (const string) 确定用于 qty 参数的值在strategy.entry或strategy.order函数中表示的内容。可能的值是:strategy.fixed表示合约/股票/手数,strategy.cash表示货币金额,或strategy.percent_of_equity表示可用权益的百分比。
  • default_qty_value (const int/float) strategy.entry或strategy.order函数的默认交易数量,当它们的 'qty' 参数未定义时,其单位由与 'default_qty_type' 参数一起使用的参数确定。
  • currency (const string) 此策略的帐户货币。可选。默认值是图表上商品的货币。可能的值: currency.NONE, currency.USD, currency.EUR, currency.AUD, currency.GBP, currency.NZD, currency.CAD, currency.CHF, currency.HKD, currency.JPY, currency.NOK, currency.SEK, currency.SGD, currency.TRY, currency.ZAR, currency.BTC, currency.ETH, currency.MYR, currency.KRW。
  • slippage (const int) 以tick为报价单位的滑点,会从买/卖市价单或止损单的成交价格中增加/减去。如果mintick = 0.01并且滑点= 5,则总滑点将为5 * 0.01 = 0.05。
  • commission_type (const string) 每个订单的佣金类型。 允许的值为:strategy.commission.percent(订单现金量的百分比),strategy.commission.cash_per_contract(以每份合约的账户货币显示金额),strategy.commission.cash_per_order (按每个订单的账户货币显示金额)。
  • commission_value (const int/float) 订单佣金值。取决于所选择的类型 (佣金类型)包括百分比或金额。
  • process_orders_on_close (const bool) 设置为“true”时,会在蜡烛图收盘并完成策略计算后生成执行订单的其他尝试。 如果订单是市价订单,则经纪商模拟器会在下一个蜡烛图开盘前执行它们。 如果订单是限价单,则只有在满足价格条件时才会执行订单。 如果要关闭当前蜡烛图的仓位,此选项很有用。 默认值为“false”。
  • close_entries_rule (const string) 确定订单关闭的顺序。允许的值为:'FIFO' 或 'ANY'。FIFO(先入先出;First-In, First-Out)意味着当多个交易开放时,必须先关闭最早的交易。此规则适用于股票、期货和美国外汇(NFA合规规则2-43b)。 'ANY' 意味着交易可以任何顺序关闭;这在非美国外汇交易中是允许的。默认值为 'FIFO'。
  • max_lines_count (const int) 显示最近的线条图数量。默认值为50,最大允许值为500。
  • max_labels_count (const int) 显示最近的标签图数量。默认值为50,最大允许值为500。
  • max_boxes_count (const int) 显示的最后box绘图的数量。默认值为50,允许的最大值为500。
  • margin_long (const int/float) 多头保证金是多头仓位必须以现金或抵押品覆盖的证券购买价格的百分比。必须是非负数。可选。默认值为100。
  • margin_short (const int/float) 空头保证金是空头仓位必须以现金或抵押品覆盖的证券购买价格的百分比。必须是非负数。可选。默认值为100。
  • explicit_plot_zorder (const bool) 指定指标的绘图、填充和水平线的呈现顺序。如果为true,将根据它们在指标代码中出现的顺序绘制图表,每个较新的图表都绘制在之前的图表之上。这仅适用于plot*()函数、fill和hline。可选。默认值为'false’。
  • initial_capital (const int/float) 最初可用于策略交易的资金量,以“货币”中定义的货币表示。可选。默认值为1000000。
  • risk_free_rate (const int/float) 无风险收益率是风险最小或为零的投资价值的年度百分比变化,用于计算 Sharpe和Sortino比率。默认值为2。

备注
每个策略脚本必须有一个 strategy 调用。
使用参数calc_on_every_tick = true的PineScript代码可以对历史记录和实时数据进行不同的计算。
当使用非标准类型的图表作为策略基础时,你需要知道结果会有所不同。订单将在该表的价格执行(e.g.for Heikin Ashi将使用Heikin Ashi的价格(平均的)不是真正的市场价格)。因此,我们强烈建议您在您的策略中使用标准图表类型。

另见
indicator

strategy.entry

这是进入市场的命令。 如果具有相同ID的订单已经挂起,则可修改订单。 如果没有指定ID的订单,则会发出新的订单。 要停用进场指令,应使用命令strategy.cancel或strategy.cancel_all。 与函数strategy.order相比,strategy.entry功能受金字塔影响,可以正确反转市场位置。 如果“Limit”和“stop”参数均为“NaN”,则订单类型为市场订单。

strategy.entry(id, direction, qty, limit, stop, oca_name, oca_type, comment, when, alert_message) 

例子

strategy(title = "simple strategy entry example")
strategy.entry("enter long", strategy.long, 1, when = open > high[1]) // enter long by market if current open great then previous high
strategy.entry("enter short", strategy.short, 1, when = open < low[1]) // enter short by market if current open less then previous low

参数

  • id (series string) 必要参数。 订单标识符。 可以通过引用其标识来取消或修改订单。
  • direction (strategy_direction) 一个必需的参数。市场持仓方向:'strategy.long'为多头,'strategy.short'为空头。
  • qty (series int/float) 可选参数。交易的合约/股数/手数/单位数量。预设值为'NaN'。
  • limit (series int/float) 可选参数。订单的限价。若已指定,订单类型是"limit" 或"stop-limit"。其他订单类型为"NaN"。
  • stop (series int/float) 可选参数。订单的止损价。如果已指定,订单类型为"stop"或"stop-limit"。其他订单类型则为"NaN"。
  • oca_name (series string) 可选参数。 该订单属于OCA集团名。 如果订单不属于任何OCA集团,则应该有一个空字符。注意:FMZ不支持此参数。
  • oca_type (input string) 可选参数。 OCA订单组类型。 允许的值为:strategy.oca.none - 订单不应属于任何特定OCA组; strategy.oca.cancel - 订单应属于OCA组,一旦订单被成交,同一组的所有其他订单将被取消; strategy.oca.reduce - 订单应属于OCA组别,如果订单合同的X数量已被放置,则同一OCA组的其他订单合同数减少X。注意:FMZ不支持此参数。
  • comment (series string) 可选参数。订单的其他说明。
  • when (series bool) 可选参数。订单的状况。若为"true",订单被放置。若为"false",则没有任何事情发生(之前放置的相同 ID 的订单没有被撤销)。默认值为"true"。
  • alert_message (series string) 当在“创建警报”对话框的“消息”字段中使用{{strategy.order.alert_message}}占位符时,一个可选参数。

strategy.close

这是一个具有指定ID的退出订单的命令。 如果有多个具有相同ID的进场订单,则它们都将同一时间退出。 如果在触发命令时没有指定ID的开放订单,该命令则不会生效。 该命令使用市场订单。 每个进场都由分开的市场订单关闭。

strategy.close(id, when, comment, qty, qty_percent, alert_message) 

例子

strategy("closeEntry Demo", overlay=false)
strategy.entry("buy", strategy.long, when = open > close)
strategy.close("buy", when = open < close, qty_percent = 50, comment = "close buy entry for 50%")
plot(strategy.position_size)

参数

  • id (series string) 必要参数。 订单标识符。可以通过引用其标识来关闭订单。
  • when (series bool) 可选参数。命令的条件。
  • qty (series int/float) 可选参数。退出交易的合约/股数/手数/单位的数量。默认值为'NaN'。
  • qty_percent (series int/float) 定义平仓的百分比(0-100)。它的优先级低于 'qty' 参数的优先级。可选。默认值为100。
  • comment (series string) 可选参数。订单的其他说明。
  • alert_message (series string) 当在“创建警报”对话框的“消息”字段中使用{{strategy.order.alert_message}}占位符时,一个可选参数。

strategy.close_all

退出当前市场仓位,使其持平。

strategy.close_all(when, comment, alert_message) 

例子

strategy("closeAll Demo", overlay=false)
strategy.entry("buy", strategy.long, when = open > close)
strategy.close_all(when = open < close, comment = "close all entries")
plot(strategy.position_size)

参数

  • when (series bool) 可选参数。命令的条件。
  • comment (series string) 可选参数。订单的其他说明。
  • alert_message (series string) 当在“创建警报”对话框的“消息”字段中使用{{strategy.order.alert_message}}占位符时,一个可选参数。

strategy.exit

这是一个退出指定进场或整个市场地位的命令。 如果具有相同ID的订单已经挂起,则可修改订单。 如果进场订单未成交,但是出现退场订单,该退场订单将暂待,直到进场订单成交后方可放置退场订单。 要停用退场订单,应使用命令strategy.cancel或strategy.cancel_all。 如果函数strategy.exit被调用一次,则只会退出一次。 如果要退出多次,应该多次调用命令strategy.exit。 如果您使用止损和追踪止损,其订单类型是“stop”,只有其中一个会被放置(会首先被成交)。 如果以下所有参数 'profit', 'limit', 'loss', 'stop', 'trail_points', 'trail_offset' 皆为“NaN”,则命令将失败。 要使用市场订单离场,应使用命令strategy.close或strategy.close_all。

strategy.exit(id, from_entry, qty, qty_percent, profit, limit, loss, stop, trail_price, trail_points, trail_offset, oca_name, comment, when, alert_message) 

例子

strategy(title = "simple strategy exit example")
strategy.entry("long", strategy.long, 1, when = open > high[1]) // enter long by market if current open great then previous high
strategy.exit("exit", "long", profit = 10, loss = 5) // generate full exit bracket (profit 10 points, loss 5 points per contract) from entry with name "long"

参数

  • id (series string) 必要参数。 订单标识符。 可以通过引用其标识来取消或修改订单。
  • from_entry (series string) 可选参数。以指定进场指令标识符退出。 要退出所有头寸,应使用空字符串。 默认值为空字符串。
  • qty (series int/float) 可选参数。退出交易的合约/股数/手数/单位的数量。默认值为'NaN'。
  • qty_percent (series int/float) 定义平仓的百分比(0-100)。它的优先级低于 'qty' 参数的优先级。可选。默认值为100。
  • profit (series int/float) 可选参数。 利润目标(以点表示)。 如果已指定,当达到指定的利润额(点)时,则以限价订单退出市场头寸。 默认值为“NaN”。
  • limit (series int/float) 可选参数。 利润目标(需指定价格)。 若已指定,则以指定价格(或更好)退出市场头寸。 参数'limit'的优先级高于参数'profit'的优先级(若值非'NaN',则'limit'取代'profit')。 默认值为“NaN”。
  • loss (series int/float) 可选参数。 止损(以点表示)。 如果已指定,当达到指定的亏损额(点)时,则以停损单退出市场头寸。 默认值为“NaN”。
  • stop (series int/float) 可选参数。 止损(需指定价格)。 如果已指定,则将以指定价格(或更差)退出市场头寸。 参数'止损'的优先级高于参数'损失'的优先级(若值非'NaN',则'止损'代替'损失')。 默认值为“NaN”。
  • trail_price (series int/float) 可选参数。跟踪止损激活水平(需指定价格)。如果已指定,当达到指定价格水平时,将放置跟踪止损单。在“trail_offset”参数中指定用于确定跟踪止损单初始价格的偏移量(以点计):X 点低于激活水平以退出多头; X点高于激活水平以退出空头。默认值为“NaN”。
  • trail_points (series int/float) 可选参数。跟踪止损激活水平(利润以点表示)。如果已指定,当达到已计算价格水平(指定利润金额)时,将放置跟踪止损单。在“trail_offset”参数中指定用于确定跟踪止损单初始价格的偏移量(以点计):X 点低于激活水平以退出多头; X点高于激活水平以退出空头。默认值为“NaN”。
  • trail_offset (series int/float) 可选参数。跟踪止损激活水平(以点表示)。以点计的偏移量用于确定跟踪止损单的初始价格:X 点低于'trail_price' or 'trail_points'以退出多头; X点高于 'trail_price' or 'trail_points'以退出空头。默认值为“NaN”。
  • oca_name (series string) 可选参数。OCA group的名称 (oca_type = strategy.oca.reduce) 获利目标,止损/跟踪止损。如果未指定名称,将自动生成该名称。注意:FMZ不支持此参数。
  • comment (series string) 可选参数。订单的其他说明。
  • when (series bool) 可选参数。订单的状况。若为"true",订单被放置。若为"false",则没有任何事情发生(之前放置的相同 ID 的订单没有被撤销)。默认值为"true"。
  • alert_message (series string) 当在“创建警报”对话框的“消息”字段中使用{{strategy.order.alert_message}}占位符时,一个可选参数。

strategy.cancel

这是引用名称来取消/停用所有预挂单的命令,由以下功能生成:strategy.order, strategy.entry and strategy.exit。

strategy.cancel(id, when) 

例子

strategy(title = "simple order cancellation example")
conditionForBuy = open > high[1]
strategy.entry("long", strategy.long, 1, limit = low, when = conditionForBuy) // enter long using limit order at low price of current bar if conditionForBuy is true
strategy.cancel("long", when = not conditionForBuy) // cancel the entry order with name "long" if conditionForBuy is false

参数

  • id (series string) 必选参数。订单标识。定位该标识以撤销一个订单。
  • when (series bool) 可选参数。根据 ID 取消一个订单。若为"true",该订单将被取消。默认值为"true"。

strategy.cancel_all

这是取消/停用所有预挂单命令,由以下功能生成:strategy.order,strategy.entry和strategy.exit。

strategy.cancel_all(when) 

例子

strategy(title = "simple all orders cancellation example")
conditionForBuy1 = open > high[1]
strategy.entry("long entry 1", strategy.long, 1, limit = low, when = conditionForBuy1) // enter long by limit if conditionForBuy1 is true
conditionForBuy2 = conditionForBuy1 and open[1] > high[2]
strategy.entry("long entry 2", strategy.long, 1, limit = ta.lowest(low, 2), when = conditionForBuy2) // enter long by limit if conditionForBuy2 is true
conditionForStopTrading = open < ta.lowest(low, 2)
strategy.cancel_all(conditionForStopTrading) // cancel both limit orders if the conditon conditionForStopTrading is true

参数

  • when (series bool) 可选参数。取消所有订单的条件。如果条件为真,则所有活动订单将被取消。默认值为“true”。

strategy.order

这是下订单的命令。 如果具有相同ID的订单已经挂起,则可以修改订单。 如果没有指定ID的订单,则会发出新的订单。 要停止订单,应使用命令strategy.cancel或strategy.cancel_all。 与函数strategy.entry相比,函数strategy.order不受金字塔形式的影响。 如果“限制”和“止损”参数均为“NaN”,则订单类型为市场订单。

strategy.order(id, direction, qty, limit, stop, oca_name, oca_type, comment, when, alert_message)

例子

strategy(title = "simple strategy order example")
strategy.order("buy", strategy.long, 1, when = open > high[1]) // buy by market if current open great then previous high
strategy.order("sell", strategy.short, 1, when = open < low[1]) // sell by market if current open less then previous low

参数

  • id (series string) 必要参数。 订单标识符。 可以通过引用其标识来取消或修改订单。
  • direction (strategy_direction) 一个必需的参数。订单方向:'strategy.long'为买入,'strategy.short'为卖出。
  • qty (series int/float) 可选参数。交易的合约/股数/手数/单位数量。预设值为'NaN'。
  • limit (series int/float) 可选参数。订单的限价。若已指定,订单类型是"limit" 或"stop-limit"。其他订单类型为"NaN"。
  • stop (series int/float) 可选参数。订单的止损价。如果已指定,订单类型为"stop"或"stop-limit"。其他订单类型则为"NaN"。
  • oca_name (series string) 可选参数。 该订单属于OCA集团名。 如果订单不属于任何OCA集团,则应该有一个空字符。注意:FMZ不支持此参数。
  • oca_type (input string) 可选参数。 OCA订单组类型。 允许的值为:strategy.oca.none - 订单不应属于任何特定OCA组; strategy.oca.cancel - 订单应属于OCA组,一旦订单被成交,同一组的所有其他订单将被取消; strategy.oca.reduce - 订单应属于OCA组别,如果订单合同的X数量已被放置,则同一OCA组的其他订单合同数减少X。注意:FMZ不支持此参数。
  • comment (series string) 可选参数。订单的其他说明。
  • when (series bool) 可选参数。订单的状况。若为"true",订单被放置。若为"false",则没有任何事情发生(之前放置的相同 ID 的订单没有被撤销)。默认值为"true"。
  • alert_message (series string) 当在“创建警报”对话框的“消息”字段中使用{{strategy.order.alert_message}}占位符时,一个可选参数。

strategy.opentrades.entry_bar_index

返回未平仓交易入场的bar_index。

strategy.opentrades.entry_bar_index(trade_num)

等待10根K线并平仓

例子

strategy("`strategy.opentrades.entry_bar_index` Example")

barsSinceLastEntry() =>
    strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) : na

// Enter a long position if there are no open positions.
if strategy.opentrades == 0
    strategy.entry("Long",  strategy.long)

// Close the long position after 10 bars. 
if barsSinceLastEntry() >= 10
    strategy.close("Long")

参数

  • trade_num (series int) 未平仓交易的交易编号。第一笔交易的编号为零。

另见
strategy.closedtrades.entry_bar_index strategy.closedtrades.exit_bar_index

strategy.opentrades.entry_id

返回未平仓交易的入场的ID。

strategy.opentrades.entry_id(trade_num)

例子

strategy("`strategy.opentrades.entry_id` Example", overlay = true)

// We enter a long position when 14 period sma crosses over 28 period sma.
// We enter a short position when 14 period sma crosses under 28 period sma.
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))

// Strategy calls to enter a long or short position when the corresponding condition is met.
if longCondition
    strategy.entry("Long entry at bar #" + str.tostring(bar_index), strategy.long)
if shortCondition
    strategy.entry("Short entry at bar #" + str.tostring(bar_index), strategy.short)

// Display ID of the latest open position.
if barstate.islastconfirmedhistory
    runtime.log("Last opened position is " + strategy.opentrades.entry_id(strategy.opentrades - 1))

返回值
返回未平仓交易的入场的ID。

参数

  • trade_num (series int) 未平仓交易的交易编号。第一笔交易的编号为零。

备注
如果 trade_num 不在范围内,则该函数返回 na:0 到 strategy.opentrades-1。

另见
strategy.opentrades.entry_bar_index strategy.opentrades.entry_time

strategy.opentrades.entry_price

返回未平仓交易的入场价格。

strategy.opentrades.entry_price(trade_num)

例子

strategy("strategy.closedtrades.entry_price Example 1")

// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
    strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
    strategy.close("Long")

// Return the entry price for the latest closed trade.
entryPrice = strategy.closedtrades.entry_price(strategy.closedtrades - 1)

plot(entryPrice, "Long entry price")

计算平均未平仓价格

例子

strategy("strategy.opentrades.entry_price Example 2", pyramiding = 2)

// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
    strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
    strategy.close("Long")

// Calculate average open position price.
avgOpenPositionPrice() =>
    sumOpenPositionPrice = 0.0
    for tradeNo = 0 to strategy.opentrades - 1
        sumOpenPositionPrice += strategy.opentrades.entry_price(tradeNo) * strategy.opentrades.size(tradeNo) / strategy.position_size
    result = nz(sumOpenPositionPrice / strategy.opentrades)

plot(avgOpenPositionPrice())

参数

  • trade_num (series int) 未平仓交易的交易编号。第一笔交易的编号为零。

另见
strategy.closedtrades.exit_price

strategy.opentrades.entry_time

返回未平仓交易入场的UNIX时间。

strategy.opentrades.entry_time(trade_num)

例子

strategy("strategy.opentrades.entry_time Example")

// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
    strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
    strategy.close("Long")

// Calculates duration in milliseconds since the last position was opened.
timeSinceLastEntry()=>
    strategy.opentrades > 0 ? (time - strategy.opentrades.entry_time(strategy.opentrades - 1)) : na

plot(timeSinceLastEntry() / 1000 * 60 * 60 * 24, "Days since last entry")

参数

  • trade_num (series int) 未平仓交易的交易编号。第一笔交易的编号为零。

另见
strategy.closedtrades.entry_time strategy.closedtrades.exit_time

strategy.opentrades.profit

返回未平仓交易的盈亏。损失表示为负值。

strategy.opentrades.profit(trade_num)

返回最后开仓交易的利润

例子

strategy("`strategy.opentrades.profit` Example 1", commission_type = strategy.commission.percent, commission_value = 0.1)

// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
    strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
    strategy.close("Long")

plot(strategy.opentrades.profit(strategy.opentrades - 1), "Profit of the latest open trade")

计算所有未平仓交易的利润

例子

strategy("`strategy.opentrades.profit` Example 2", pyramiding = 5)

// Strategy calls to enter 5 long positions every 2 bars.
if bar_index % 2 == 0
    strategy.entry("Long", strategy.long, qty = 5)

// Calculate open profit or loss for the open positions.
tradeOpenPL() =>
    sumProfit = 0.0
    for tradeNo = 0 to strategy.opentrades - 1
        sumProfit += strategy.opentrades.profit(tradeNo)
    result = sumProfit
    
plot(tradeOpenPL(), "Profit of all open trades")

参数

  • trade_num (series int) 未平仓交易的交易编号。第一笔交易的编号为零。

另见
strategy.closedtrades.profit strategy.openprofit strategy.netprofit strategy.grossprofit

strategy.opentrades.size

返回未平仓交易中的交易方向和合约数量。如果该值>0,则市场仓位为多头。如果该值<0,则市场仓位为空头。

strategy.opentrades.size(trade_num)

例子

strategy("`strategy.opentrades.size` Example 1")

// We calculate the max amt of shares we can buy.
amtShares = math.floor(strategy.equity / close)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars
if bar_index % 15 == 0
    strategy.entry("Long", strategy.long, qty = amtShares)
if bar_index % 20 == 0
    strategy.close("Long")

// Plot the number of contracts in the latest open trade.
plot(strategy.opentrades.size(strategy.opentrades - 1), "Amount of contracts in latest open trade")

计算未平仓交易的平均利润百分比

例子

strategy("`strategy.opentrades.size` Example 2")

// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
    strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
    strategy.close("Long")

// Calculate profit for all open trades.
profitPct = 0.0
for tradeNo = 0 to strategy.opentrades - 1
    entryP = strategy.opentrades.entry_price(tradeNo)
    exitP = close
    profitPct += (exitP - entryP) / entryP * strategy.opentrades.size(tradeNo) * 100
    
// Calculate average profit percent for all open trades.
avgProfitPct = nz(profitPct / strategy.opentrades)

参数

  • trade_num (series int) 未平仓交易的交易编号。第一笔交易的编号为零。

另见
strategy.closedtrades.size strategy.position_size strategy.opentrades strategy.closedtrades

strategy.closedtrades.entry_bar_index

返回已平仓交易入场的bar_index。

strategy.closedtrades.entry_bar_index(trade_num)

例子

strategy("strategy.closedtrades.entry_bar_index Example")
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
    strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
    strategy.close("Long")
// Function that calculates the average amount of bars in a trade.
avgBarsPerTrade() =>
    sumBarsPerTrade = 0
    for tradeNo = 0 to strategy.closedtrades - 1
        // Loop through all closed trades, starting with the oldest.
        sumBarsPerTrade += strategy.closedtrades.exit_bar_index(tradeNo) - strategy.closedtrades.entry_bar_index(tradeNo) + 1
    result = nz(sumBarsPerTrade / strategy.closedtrades)
plot(avgBarsPerTrade())

参数

  • trade_num (series int) 已平仓交易的交易编号。第一笔交易的编号为零。

另见
strategy.closedtrades.exit_bar_index strategy.opentrades.entry_bar_index

strategy.closedtrades.exit_price

返回已平仓交易的出场价格。

strategy.closedtrades.exit_price(trade_num)

例子

strategy("strategy.closedtrades.exit_price Example 1")

// We are creating a long trade every 5 bars
if bar_index % 5 == 0
    strategy.entry("Long",  strategy.long)
strategy.close("Long")

// Return the exit price from the latest closed trade.
exitPrice = strategy.closedtrades.exit_price(strategy.closedtrades - 1)

plot(exitPrice, "Long exit price")

计算所有已平仓交易的平均利润百分比

例子

strategy("strategy.closedtrades.exit_price Example 2")

// Strategy calls to create single short and long trades.
if bar_index == last_bar_index - 15
    strategy.entry("Long Entry",  strategy.long)
else if bar_index == last_bar_index - 10
    strategy.close("Long Entry")
    strategy.entry("Short", strategy.short)
else if bar_index == last_bar_index - 5
    strategy.close("Short")

// Calculate profit for both closed trades.
profitPct = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
    entryP = strategy.closedtrades.entry_price(tradeNo)
    exitP = strategy.closedtrades.exit_price(tradeNo)
    profitPct += (exitP - entryP) / entryP * strategy.closedtrades.size(tradeNo) * 100
    
// Calculate average profit percent for both closed trades.
avgProfitPct = nz(profitPct / strategy.closedtrades)

plot(avgProfitPct)

参数

  • trade_num (series int) 已平仓交易的交易编号。第一笔交易的编号为零。

另见
strategy.closedtrades.entry_price

strategy.closedtrades.exit_bar_index

返回已平仓交易退出的bar_index。

strategy.closedtrades.exit_bar_index(trade_num)

例子

strategy("strategy.closedtrades.exit_bar_index Example 1")

// Strategy calls to place a single short trade. We enter the trade at the first bar and exit the trade at 10 bars before the last chart bar.
if bar_index == 0
    strategy.entry("Short",  strategy.short)
if bar_index == last_bar_index - 10
    strategy.close("Short")

// Calculate the amount of bars since the last closed trade.
barsSinceClosed = strategy.closedtrades > 0 ? bar_index - strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1) : na

plot(barsSinceClosed, "Bars since last closed trade")

计算每笔交易的平均K线数。

例子

strategy("strategy.closedtrades.exit_bar_index Example 2")

// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
    strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
    strategy.close("Long")

// Function that calculates the average amount of bars per trade.
avgBarsPerTrade() =>
    sumBarsPerTrade = 0
    for tradeNo = 0 to strategy.closedtrades - 1
        // Loop through all closed trades, starting with the oldest.
        sumBarsPerTrade += strategy.closedtrades.exit_bar_index(tradeNo) - strategy.closedtrades.entry_bar_index(tradeNo) + 1
    result = nz(sumBarsPerTrade / strategy.closedtrades)

plot(avgBarsPerTrade())

参数

  • trade_num (series int) 已平仓交易的交易编号。第一笔交易的编号为零。

另见
bar_index

strategy.closedtrades.entry_id

返回已平仓交易的入场的id。

strategy.closedtrades.entry_id(trade_num)

例子

strategy("strategy.closedtrades.entry_id Example", overlay = true)
var isOpen = false 
var openIndex = -1
// Enter a short position and close at the previous to last bar.
if not barstate.ishistory and not isOpen
    strategy.entry("Short at bar #" + str.tostring(bar_index), strategy.short)
    isOpen := true
    openIndex := bar_index
if openIndex != -1 and bar_index > openIndex + 100
    strategy.close_all()
    
// Display ID of the last entry position.
if barstate.islastconfirmedhistory
    runtime.log("Last Entry ID is: " + strategy.closedtrades.entry_id(strategy.closedtrades - 1))

返回值
返回已平仓交易的入场的id。

参数

  • trade_num (series int) 已平仓交易的交易编号。第一笔交易的编号为零。

备注
如果 trade_num 不在范围内,则该函数返回 na:0 到 strategy.closedtrades-1。

另见
strategy.closedtrades.entry_bar_index strategy.closedtrades.entry_time

strategy.closedtrades.entry_price

返回已平仓交易的入场价格。

strategy.closedtrades.entry_price(trade_num)

例子

strategy("strategy.closedtrades.entry_price Example 1")

// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
    strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
    strategy.close("Long")

// Return the entry price for the latest  entry.
entryPrice = strategy.closedtrades.entry_price(strategy.closedtrades - 1)

plot(entryPrice, "Long entry price")

计算所有已平仓交易的平均利润百分比

例子

strategy("strategy.closedtrades.entry_price Example 2")

// Strategy calls to create single short and long trades
if bar_index == last_bar_index - 15
    strategy.entry("Long Entry",  strategy.long)
else if bar_index == last_bar_index - 10
    strategy.close("Long Entry")
    strategy.entry("Short", strategy.short)
else if bar_index == last_bar_index - 5
    strategy.close("Short")

// Calculate profit for both closed trades.
profitPct = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
    entryP = strategy.closedtrades.entry_price(tradeNo)
    exitP = strategy.closedtrades.exit_price(tradeNo)
    profitPct += (exitP - entryP) / entryP * strategy.closedtrades.size(tradeNo) * 100
    
// Calculate average profit percent for both closed trades.
avgProfitPct = nz(profitPct / strategy.closedtrades)

plot(avgProfitPct)

参数

  • trade_num (series int) 已平仓交易的交易编号。第一笔交易的编号为零。

另见
strategy.closedtrades.exit_price strategy.closedtrades.size strategy.closedtrades

strategy.closedtrades.entry_time

返回已平仓交易入场的UNIX时间。

strategy.closedtrades.entry_time(trade_num)

例子

strategy("strategy.closedtrades.entry_time Example", overlay = true)

// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
    strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
    strategy.close("Long")

// Calculate the average trade duration 
avgTradeDuration() =>
    sumTradeDuration = 0
    for i = 0 to strategy.closedtrades - 1
        sumTradeDuration += strategy.closedtrades.exit_time(i) - strategy.closedtrades.entry_time(i)
    result = nz(sumTradeDuration / strategy.closedtrades)

// Display average duration converted to seconds and formatted using 2 decimal points
if barstate.islastconfirmedhistory
    runtime.log(str.tostring(avgTradeDuration() / 1000, "#.##") + " seconds")

参数

  • trade_num (series int) 已平仓交易的交易编号。第一笔交易的编号为零。

另见
strategy.opentrades.entry_time strategy.closedtrades.exit_time time

strategy.closedtrades.profit

返回已平仓交易的盈亏。损失表示为负值。

strategy.closedtrades.profit(trade_num)

例子

strategy("`strategy.closedtrades.profit` Example")

// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
    strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
    strategy.close("Long")

// Calculate average gross profit by adding the difference between gross profit and commission.
avgGrossProfit() =>
    sumGrossProfit = 0.0
    for tradeNo = 0 to strategy.closedtrades - 1
        sumGrossProfit += strategy.closedtrades.profit(tradeNo) - strategy.closedtrades.commission(tradeNo)
    result = nz(sumGrossProfit / strategy.closedtrades)
    
plot(avgGrossProfit(), "Average gross profit")

参数

  • trade_num (series int) 已平仓交易的交易编号。第一笔交易的编号为零。

另见
strategy.opentrades.profit strategy.closedtrades.commission

strategy.closedtrades.size

返回已平仓交易中的交易方向和合约数量。如果该值>0,则市场仓位为多头。 如果该值<0,则市场仓位为空头。

strategy.closedtrades.size(trade_num)

例子

strategy("`strategy.closedtrades.size` Example 1")

// We calculate the max amt of shares we can buy.
amtShares = math.floor(strategy.equity / close)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars
if bar_index % 15 == 0
    strategy.entry("Long", strategy.long, qty = amtShares)
if bar_index % 20 == 0
    strategy.close("Long")

// Plot the number of contracts traded in the last closed trade.     
plot(strategy.closedtrades.size(strategy.closedtrades - 1), "Number of contracts traded")

计算平仓交易的平均利润百分比

例子

strategy("`strategy.closedtrades.size` Example 2")

// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
    strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
    strategy.close("Long")


// Calculate profit for both closed trades.
profitPct = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
    entryP = strategy.closedtrades.entry_price(tradeNo)
    exitP = strategy.closedtrades.exit_price(tradeNo)
    profitPct += (exitP - entryP) / entryP * strategy.closedtrades.size(tradeNo) * 100
    
// Calculate average profit percent for both closed trades.
avgProfitPct = nz(profitPct / strategy.closedtrades)

plot(avgProfitPct)

参数

  • trade_num (series int) 已平仓交易的交易编号。第一笔交易的编号为零。

另见
strategy.opentrades.size strategy.position_size strategy.closedtrades strategy.opentrades

strategy.closedtrades.exit_time

返回已平仓交易退出的UNIX时间。

strategy.closedtrades.exit_time(trade_num)

例子

strategy("strategy.closedtrades.exit_time Example 1")

// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
    strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
    strategy.close("Long")

// Calculate the average trade duration. 
avgTradeDuration() =>
    sumTradeDuration = 0
    for i = 0 to strategy.closedtrades - 1
        sumTradeDuration += strategy.closedtrades.exit_time(i) - strategy.closedtrades.entry_time(i)
    result = nz(sumTradeDuration / strategy.closedtrades)

// Display average duration converted to seconds and formatted using 2 decimal points.
if barstate.islastconfirmedhistory
    label.new(bar_index, high, str.tostring(avgTradeDuration() / 1000, "#.##") + " seconds")

X秒后重新打开已平仓交易

例子

strategy("strategy.closedtrades.exit_time Example 2")

// Strategy calls to emulate a single long trade at the first bar.
if bar_index == 0
    strategy.entry("Long", strategy.long)

reopenPositionAfter(timeSec) =>
    if strategy.closedtrades > 0
        if time - strategy.closedtrades.exit_time(strategy.closedtrades - 1) >= timeSec * 1000
            strategy.entry("Long", strategy.long)

// Reopen last closed position after 120 sec.                
reopenPositionAfter(120)

if ta.change(strategy.opentrades)
    strategy.exit("Long", stop = low * 0.9, profit = high * 2.5)

参数

  • trade_num (series int) 已平仓交易的交易编号。第一笔交易的编号为零。

另见
strategy.closedtrades.entry_time

strategy.risk.allow_entry_in

此函数可用于指定strategy.entry函数允许在哪个市场方向开仓。

strategy.risk.allow_entry_in(value)

例子

strategy("strategy.risk.allow_entry_in")

strategy.risk.allow_entry_in(strategy.direction.long)
strategy.entry("Long", strategy.long, when = open > close)
// Instead of opening a short position with 10 contracts, this command will close long entries.
strategy.entry("Short", strategy.short, when = open < close, qty = 10)

参数

  • value (simple string) 允许的方向。可能的值:strategy.direction.allstrategy.direction.longstrategy.direction.short

strategy.risk.max_position_size

此规则的目的是确定市场头寸的最大值。 该规则影响以下功能:strategy.entry。 “entry”数量可以减少(如果需要)到合同/股/手/单位数,所以头寸总值不超过'strategy.risk.max_position_size'中指定的值。如果最低数量仍然违反规则,则不会放置订单。

strategy.risk.max_position_size(contracts)

例子

strategy("risk.max_position_size Demo", default_qty_value = 100)
strategy.risk.max_position_size(10)
strategy.entry("buy", strategy.long, when = open > close)
plot(strategy.position_size)  // max plot value will be 10

参数

  • contracts (simple int/float) 必要参数。仓位的合同/股/手/单位的最大数。

math

math.abs

如果 number >= 0,number 的绝对值为 number,否则为 -number

math.abs(number) 

返回值
number的绝对值。

math.acos

acos函数返回数字的反余弦(以弧度表示),如cos(acos(y)) = y 在 y 范围内 [-1, 1]。

math.acos(angle)

返回值
反余弦值。如果y超出范围[-1,1],返回角度在[0,Pi]或na的范围内。

math.random

返回伪随机值。该函数将为每个脚本执行生成不同的值序列。对可选的seed参数使用相同的值将产生可重复的序列。

math.random(min, max, seed)

返回值
一个随机值。

参数

  • min (series int/float) 随机值范围的下限。该值不包括在范围内。默认值为0。
  • max (series int/float) 随机值范围的上限。该值不包括在范围内。默认值为1。
  • seed (input int) 可选参数。当使用相同的seed时,允许连续调用该函数以产生一组可重复的值。

math.asin

asin函数返回数字的反正弦(以弧度表示),正弦(asin(y)) = y 在 y 范围内[-1, 1]。

math.asin(angle) 

返回值
反正弦值。如果y超出范围[-1,1],返回角度在[-Pi / 2,Pi / 2]或na的范围内。

math.atan

atan函数返回数字的反正切(以弧度表示),tan(atan(y)) = 任何 y 中的 y。

math.atan(angle) 

返回值
反正切值; 返回角度在[-Pi / 2,Pi / 2]的范围内。

math.ceil

向上取整函数返回大于或等于参数的最小(最接近负无穷)整数。

math.ceil(number)

返回值
小于或等于给定数字的最小整数

另见
math.floor math.round

math.cos

cos函数返回角度的三角余弦。

math.cos(angle) 

返回值
角的三角余弦。

参数

  • angle (series int/float) 角度,以弧度

math.exp

number 的 exp 函数是 e 的 number 次方,其中 e 是欧拉数。

math.exp(number) 

返回值
一个表示 e 的值,它是 number 的幂。

另见
math.pow

math.floor

math.floor(number) 

返回值
小于或等于给定数字的最大整数。

另见
math.ceil math.round

math.log

任何 number > 0 的自然对数是唯一的 y,使得 e^y = number

math.log(number)

返回值
number的自然对数。

另见
math.log10

math.log10

number的常用(或以10为底的)对数是必须将10提高到的幂才能获得number。10^y = number

math.log10(number)

返回值
number的以10为底的对数。

另见
math.log

math.pow

数学幂函数

math.pow(base, exponent)

例子

// math.pow
plot(math.pow(close, 2))

返回值
base提高到exponent的幂。如果base是一个系列,它是按元素计算的。

参数

  • base (series int/float) 指定要使用的基础。
  • exponent (series int/float) 指定指数。

另见
math.sqrt math.exp

math.sign

如果“number”为零,则“number”的符号(signum)为零,如果“number”大于0,则为1.0,如果“number”小于0,则为-1.0。

math.sign(number)

返回值
参数的标志。

math.sin

正弦函数返回一个角度的三角正弦。

math.sin(angle)

返回值
角的三角正弦。

参数

  • angle (series int/float) 角度,以弧度

math.sqrt

任何number >= 0的平方根是唯一的y >= 0使得y^2 = number

math.sqrt(number)

返回值
number的平方根。

另见
math.pow

math.tan

tan函数返回角度的三角正切。

math.tan(angle)

返回值
角的三角正切。

参数

  • angle (series int/float) 角度,以弧度

math.round

返回 number 的值,四舍五入到最接近的整数,并向上取整。如果使用了 precision 参数,则返回一个四舍五入到小数位数的浮点值。

math.round(number) 
math.round(number, precision) 

返回值
number的值四舍五入到最接近的整数,或根据精度。

参数

  • number (series int/float) 要四舍五入的值。
  • precision (series int) 可选参数。number 将被四舍五入的小数位数。当没有提供参数时,四舍五入到最接近的整数。

备注
请注意,对于'na'值,函数返回'na'。

另见
math.ceil math.floor

math.max

返回多个值中最大的一个。

math.max(number0, number1, ...) 

例子

// math.max
plot(math.max(close, open))
plot(math.max(close, math.max(open, 42)))

返回值
多个给定值中最大的。

另见
math.min

math.min

返回多个值中最小的一个。

math.min(number0, number1, ...) 

例子

// math.min
plot(math.min(close, open))
plot(math.min(close, math.min(open, 42)))

返回值
多个给定值中的最小值。

另见
math.max

math.avg

计算所有系列的平均值(对应元素)。

math.avg(number0, number1, ...)

返回值
平均

另见
math.sum ta.cum ta.sma

math.round_to_mintick

返回四舍五入到商品的mintick的值,即可以除以syminfo.mintick的最接近的值,没有余数,并向上舍入。

math.round_to_mintick(number) 

返回值
number四舍五入以精确到tick。

参数

  • number (series int/float) 要四舍五入的值。

另见
math.ceil math.floor

math.sum

sum函数返回x的最后y值的滑动综合。

math.sum(source, length)

返回值
lengthK线返回的source总和。

参数

  • source (series int/float) 待执行的系列值。
  • length (series int) K线数量(长度).

另见
ta.cum for

math.todegrees

从以弧度为单位的角度,返回以度为单位的近似等效角度。

math.todegrees(radians) 

返回值
以度为单位的角度值。

参数

  • radians (series int/float) 以弧度为单位的角度。

math.toradians

从以度为单位的角度,返回以弧度为单位的近似等效角度。

math.toradians(degrees) 

返回值
以弧度为单位的角度值。

参数

  • degrees (series int/float) 以度为单位的角度。

others

fixnan

对于给定的系列,将NaN值替换为先前的非NaN值。

fixnan(source) 

返回值
无na间隙的系列。

参数

  • source (series int/float/bool/color)

另见
na nz

nz

以系列中的零(或指定数)替换NaN值。

nz(source, replacement) 
nz(source)

例子

// nz
plot(nz(ta.sma(close, 100)))

返回值
source的值,如果它不是na。如果source的值为na,则返回0,如果使用1,则返回replacement参数。

参数

  • source (series int/float/bool/color) 待执行的系列值。
  • replacement (series int/float/bool/color) 将替换“source”系列中的所有“na”值的值。

另见
na fixnan

na

如为NaN,则测试价值。

na(x)

返回值
如果x非有效数字,则为true(x为NaN),否则为false。

另见
fixnan nz

int

转换na或将float值截断为int。

int(x) 

返回值
转换为int后的参数值。

另见
float bool color string

float

将na设置为浮动。

float(x) 

返回值
转换为float后的参数值。

另见
int bool color string

alert

在实时K线期间调用时触发警报事件,并且之前通过“创建警报”对话框为指标或策略创建了基于警报功能事件的警报。

alert(message, freq)

例子

// alert() example
ma = ta.sma(close, 14)
xUp = ta.crossover(close, ma)
if xUp
    // Trigger the alert the first time a cross occurs during the real-time bar.
    alert("Price (" + str.tostring(close) + ") crossed over MA (" + str.tostring(ma) +  ").", alert.freq_once_per_bar)
plot(ma)
plotchar(xUp, "xUp", "▲", location.top, size = size.tiny)

参数

  • message (series string) 警报触发时发送的消息。必填参数。
  • freq (input string) 触发频率。可能的值为:alert.freq_all(所有函数调用触发警报),alert.freq_once_per_bar(K线中的第一个函数调用触发警报),alert.freq_once_per_bar_close(函数调用仅在实时K线的最后一个脚本迭代期间发生时,在关闭时才触发警报)。默认值为alert.freq_once_per_bar。

备注
帮助中心介绍了如何创建此类警报。
与alertcondition相反,alert调用不算作额外的绘图。
函数调用可以位于全局和局部范围内。
函数调用在图表上不显示任何内容。
'freq'参数仅影响使用此函数调用之处的触发频率。

另见
alertcondition

alertcondition

创建警报条件,在创建警报话框中可用。 请注意,alertcondition不会创建警报,它只会在创建警报对话框中为您提供更多选项。 此外,alertcondition效果在图表上是看不见的。

alertcondition(condition, title, message)

例子

// alertcondition
alertcondition(close >= open, title='Alert on Green Bar', message='Green Bar!')

参数

  • condition (series bool) 用于警报的系列布尔值。 True值代表警报触发,false - 无警报。 必要参数。
  • title (const string) 警报条件的标题。 可选参数。
  • message (const string) 当警报触发时显示消息。可选参数。

备注
请注意,在Pine v4中,警报条件调用会生成一个额外的图。 当我们计算每个脚本的输出系列的数量时,会考虑所有这些调用。

另见
alert

indicator

为了兼容Trading View策略代码,实际不需要调用。

另见
strategy

time

time函数返回指定时间范围和交易时段的当前K线的UNIX时间,如果时间点不在交易时段中,则返回NaN。注意:FMZ不支持session参数。

time(timeframe, session, timezone)

time(timeframe, session)

time(timeframe)

例子

timeinrange(res, sess) => not na(time(res, sess, "America/New_York")) ? 1 : 0
plot(timeinrange("1", "1300-1400"), color=color.red)

// This plots 1.0 at every start of 10 minute bar on a 1 minute chart:
newbar(res) => ta.change(time(res)) == 0 ? 0 : 1
plot(newbar("10"))

当设置某个会话时,您不仅可以指定小时与分钟,也可以指定某一周内的日期。
如果没有指定日期,则认为交易时段设置为从星期日 (1) 到星期六 (7),即“1100-2000”与“1100-1200:1234567”相同。
您可以通过指定日期来更改它。例如,对于每周7天交易且24小时交易时段的商品,以下脚本不会为周六和周日着色:

例子

// Time
t1 = time(timeframe.period, "0000-0000:23456")
bgcolor(t1 ? color.new(color.blue, 90) : na)

一个session参数可以包含多个不同的交易时段,以逗号分隔。例如,以下脚本将突出显示从10:00到11:00以及从14:00到15:00(仅限工作日)的K线图:

例子

// Time
t1 = time(timeframe.period, "1000-1100,1400-1500:23456")
bgcolor(t1 ? color.new(color.blue, 90) : na)

返回值
Unix时间。

参数

  • timeframe (simple string) 时间周期。空字符串被解释为图表的当前时间周期。
  • session (simple string) 交易时段规范。可选参数,默认情况下使用商品交易时段。空字符串被解释为商品的交易时段。FMZ不支持。
  • timezone (simple string) session参数的时区。只能在指定了“会话”时使用。可选。默认值为syminfo.timezone。可以用GMT表示法(例如“GMT-5”)或 IANA 时区数据库名称(例如“America/New_York”)指定。

备注
UNIX时间是自1970年1月1日UTC 00:00:00起已经过去的毫秒数。

year

year(time)
year(time, timezone)

返回值
提供UNIX时间的年份(交换时区)。

参数

  • time (series int) 以毫秒为单位的unix时间。
  • timezone (series string) 可选参数。时区。

备注
UNIX时间是自1970年1月1日UTC 00:00:00以来的毫秒数。默认情况下,时区为syminfo.timezone。您可以使用timestamp检查可能的值。
请注意,此函数根据K线的打开时间返回年份。对于隔夜交易时段(例如EURUSD周一交易时段从周日17:00 UTC-4开始),该值可以比交易日的年份低1。

另见
year time month dayofmonth dayofweek hour minute second

month

month(time)
month(time, timezone)

返回值
提供UNIX时间的月份(交换时区)。

参数

  • time (series int) 以毫秒为单位的unix时间。
  • timezone (series string) 可选参数。时区。

备注
UNIX时间是自1970年1月1日UTC 00:00:00以来的毫秒数。默认情况下,时区为syminfo.timezone。您可以使用timestamp检查可能的值。
请注意,此函数根据K线的打开时间返回月份。对于隔夜交易时段(例如,EURUSD周一交易时段从周日17:00 UTC-4开始),该值可以比交易日的月份低1。

另见
month time year dayofmonth dayofweek hour minute second

hour

hour(time)
hour(time, timezone)

返回值
提供UNIX时间的小时(交换时区)。

参数

  • time (series int) 以毫秒为单位的unix时间。
  • timezone (series string) 可选参数。时区。

备注
UNIX时间是自1970年1月1日UTC 00:00:00以来的毫秒数。默认情况下,时区为syminfo.timezone。您可以使用timestamp检查可能的值。

另见
hour time year month dayofmonth dayofweek minute second

minute

minute(time)
minute(time, timezone)

返回值
提供UNIX时间的分钟(交换时区)。

参数

  • time (series int) 以毫秒为单位的unix时间。
  • timezone (series string) 可选参数。时区。

备注
UNIX时间是自1970年1月1日UTC 00:00:00以来的毫秒数。默认情况下,时区为syminfo.timezone。您可以使用timestamp检查可能的值。

另见
minute time year month dayofmonth dayofweek hour second

second

second(time)
second(time, timezone)

返回值
提供UNIX时间的秒数(交换时区)。

参数

  • time (series int) 以毫秒为单位的unix时间。
  • timezone (series string) 可选参数。时区。

备注
UNIX时间是自1970年1月1日UTC 00:00:00以来的毫秒数。默认情况下,时区为syminfo.timezone。您可以使用timestamp检查可能的值。

另见
second time year month dayofmonth dayofweek hour minute

weekofyear

weekofyear(time)
weekofyear(time, timezone)

返回值
提供UNIX时间的周期(交换时区)。

参数

  • time (series int) 以毫秒为单位的unix时间。
  • timezone (series string) 可选参数。时区。

备注
UNIX时间是自1970年1月1日UTC 00:00:00以来的毫秒数。默认情况下,时区为syminfo.timezone。您可以使用timestamp检查可能的值。
请注意,该函数根据K线的打开时间返回周。对于隔夜交易时段(例如EURUSD,其周一交易时段从周日17:00开始),该值可以比交易日的周低1。该

另见
weekofyear time year month dayofmonth dayofweek hour minute second

dayofweek

dayofweek(time)
dayofweek(time, timezone)

返回值
提供UNIX时间的每周日期(交换时区)。

参数

  • time (series int) 以毫秒为单位的unix时间。
  • timezone (series string) 可选参数。时区。

备注
请注意,此函数根据K线的打开时间返回日期。对于隔夜交易时段(例如EURUSD周一交易时段从周日17:00开始),该值可以比交易日的日期低1。
UNIX时间是自1970年1月1日UTC 00:00:00以来的毫秒数。默认情况下,时区为syminfo.timezone。您可以使用timestamp检查可能的值。

另见
time dayofmonth

dayofmonth

dayofmonth(time)
dayofmonth(time, timezone)

返回值
提供UNIX时间的每月日期(交换时区)。

参数

  • time (series int) 以毫秒为单位的unix时间。
  • timezone (series string) 可选参数。时区。

备注
UNIX时间是自1970年1月1日UTC 00:00:00以来的毫秒数。默认情况下,时区为syminfo.timezone。您可以使用timestamp检查可能的值。
请注意,此函数根据K线的打开时间返回日期。对于隔夜交易时段(例如EURUSD周一交易时段从周日17:00 UTC-4开始),该值可以比交易日的日期低1。

另见
time dayofweek

timestamp

时间戳功能返回UNIX时间的指定日期和时间。

timestamp(dateString)
timestamp(year, month, day, hour, minute, second)
timestamp(timezone, year, month, day, hour, minute, second)

例子

// timestamp
plot(timestamp(2016, 01, 19, 09, 30), linewidth=3, color=color.green)
plot(timestamp(syminfo.timezone, 2016, 01, 19, 09, 30), color=color.blue)
plot(timestamp(2016, 01, 19, 09, 30), color=color.yellow)
plot(timestamp("GMT+6", 2016, 01, 19, 09, 30))
plot(timestamp(2019, 06, 19, 09, 30, 15), color=color.lime)
plot(timestamp("GMT+3", 2019, 06, 19, 09, 30, 15), color=color.fuchsia)
plot(timestamp("Feb 01 2020 22:10:05"))
plot(timestamp("2011-10-10T14:48:00"))
plot(timestamp("04 Dec 1995 00:12:00 GMT+5"))

返回值
Unix时间。

参数

  • timezone (series string) 时区。可选。默认值为syminfo.timezone。可以用GMT表示法(例如“GMT-5”)或 IANA 时区数据库名称(例如“America/New_York”)指定。
  • year (series int) 年。
  • month (series int) 月。
  • day (series int) 日。
  • hour (series int) (可选参数)小时。默认值为0。
  • minute (series int) (可选参数)分钟。默认值为0。
  • second (series int) (可选参数)Second。默认值为0。
  • dateString (const string) 一个字符串,其中包含日期以及可选的时间和时区。其格式必须符合IETF RFC 2822或ISO 8601标准(“DD MMM YYYY hh:mm:ss±hhmm”或“YYYY-MM-DDThh:mm:ss±hh:mm”,因此是“20 Feb 2020”或“2020-02-20”)。如果未提供时间,则使用“00:00”。如果未提供任何时区,则将使用GMT+0。请注意,这与函数通常的行为不同,后者返回交易所所在时区的时间。

备注
UNIX时间是自1970年1月1日UTC 00:00:00起已经过去的毫秒数。

另见
time timenow syminfo.timezone

fill

使用提供的颜色填充两个绘图或hline之间的背景。

fill(hline1, hline2, color, title, editable, fillgaps, display)
fill(plot1, plot2, color, title, editable, show_last, fillgaps, display)

例子

h1 = hline(20)
h2 = hline(10)
fill(h1, h2, color=color.new(color.blue, 90))

p1 = plot(open)
p2 = plot(close)
fill(p1, p2, color=color.new(color.green, 90))

参数

  • hline1 (hline) 首个hline对象。 必要参数。
  • hline2 (hline) 第二个hline对象。 必要参数。
  • plot1 (plot) 首个绘图对象。 必需参数。
  • plot2 (plot) 第二个绘图对象。 必要参数。
  • color (series color) 绘图的颜色。您可以使用如'color = red'或'color =#ff001a'的常量以及如 'color = close >= open ? green : red'的复杂表达式。 可选参数。
  • title (const string) 已创建填充对象的标题。 可选参数。
  • editable (const bool) 如果为true,则填充样式可在格式对话框中编辑。 默认值为true。
  • show_last (input int) 如已设置,则定义填充图表的k线数(从最后k线返回过去)。
  • fillgaps (const bool) 控制空隙的连续填充,即,当plot()调用之一返回na值时。设置为true时,最后的填充将继续填补空隙。默认为false。
  • display (plot_display) 控制填充的显示位置。可能的值为:display.none、display.all。默认为display.all。

另见
plot barcolor bgcolor hline

hline

在给定的固定价格水平上呈现水平线。

hline(price, title, color, linestyle, linewidth, editable, display)

例子

// input.hline
hline(3.14, title='Pi', color=color.blue, linestyle=hline.style_dotted, linewidth=2)

// You may fill the background between any two hlines with a fill() function:
h1 = hline(20)
h2 = hline(10)
fill(h1, h2, color=color.new(color.green, 90))

返回值
可用于fill的hline对象。

参数

  • price (input int/float) 对象将呈现的价格值。必要参数。
  • title (const string) 对象的标题
  • color (input color) 渲染线的颜色。 必须是常量(非表达式)。 可选参数。
  • linestyle (hline_style) 渲染线的样式。 可能的值有:solid,dotted,dotted。 可选参数。
  • linewidth (input int) 渲染线的宽度。默认值为1。
  • editable (const bool) 如果为true,则hline样式可在格式对话框中编辑。 默认值为true。
  • display (plot_display) 控制线的显示位置。可能的值为:display.none、display.all。默认为display.all。
  • overlay (const bool) FMZ平台扩展的参数,用于设置当前函数在主图(设置true)或者副图(设置false)上画图显示,默认值为false。不指定该参数则按照strategy或者indicator中的overlay参数设置,strategy或者indicator没有设置overlay参数,则按照默认参数处理。

bgcolor

用指定颜色填充K线的背景。

bgcolor(color, offset, editable, show_last, title, display, overlay)

例子

// bgcolor example
bgcolor(close < open ? color.new(color.red,70) : color.new(color.green, 70))

参数

  • color (series color) 填充背景的颜色。 您可以使用如“red”或“#ff001a”的常量以及像 'close >= open ? green : red'的复杂表达式。必要参数。
  • offset (series int) 在k线特定数量上向左或向右移动颜色系列。 默认值为0。
  • editable (const bool) 如果为true,则bgcolor样式可在格式对话框中编辑。 默认值为true。
  • show_last (input int) 如已设置,则定义填充图表的k线数(从最后k线返回过去)。
  • title (const string) bgcolor的标题。 可选参数。
  • display (plot_display) 控制bgcolor的显示位置。可能的值为:display.none、display.all。默认为display.all。
  • overlay (const bool) FMZ平台扩展的参数,用于设置当前函数在主图(设置true)或者副图(设置false)上画图显示,默认值为false。不指定该参数则按照strategy或者indicator中的overlay参数设置,strategy或者indicator没有设置overlay参数,则按照默认参数处理。

另见
plot

barcolor

设置K线颜色。

barcolor(color, offset, editable, show_last, title, display)

例子

barcolor(close < open ? color.black : color.white)

参数

  • color (series color) K线颜色。您可以使用如“red”或“#ff001a”的常量,以及如 'close >= open ? green : red'的复杂表达式。必要参数。
  • offset (series int) 在k线特定数量上向左或向右移动颜色系列。 默认值为0。
  • editable (const bool) 如果为true,则barcolor样式可在格式对话框中编辑。 默认值为true。
  • show_last (input int) 如已设置,则定义填充图表的k线数(从最后k线返回过去)。
  • title (const string) Barcolor标题。可选参数。
  • display (plot_display) 控制K线颜色的显示位置。可能的值为:display.none、display.all。默认为display.all。

另见
bgcolor plot fill

error

兼容PINE v4版本的error,功能与runtime.error一致。

内置变量

order

order.ascending

确定阵列从最小到最大的排序顺序。

类型
sort_order

另见
array.new_float array.sort

order.descending

确定阵列从最大到最小的排序顺序。

类型
sort_order

另见
array.new_float array.sort

timeframe

timeframe.isdaily

如果当前分辨率是每日分辨率,则返回true,否则返回false。

类型
simple bool

另见
timeframe.isdwm timeframe.isintraday timeframe.isminutes timeframe.isseconds timeframe.isweekly timeframe.ismonthly

timeframe.isdwm

如果当前分辨率是每日或每周或每月分辨率,则返回true,否则返回false。

类型
simple bool

另见
timeframe.isintraday timeframe.isminutes timeframe.isseconds timeframe.isdaily timeframe.isweekly timeframe.ismonthly

timeframe.isintraday

如果当前周期是日内(分钟或秒)周期,则返回true,否则返回false。

类型
simple bool

另见
timeframe.isminutes timeframe.isseconds timeframe.isdwm timeframe.isdaily timeframe.isweekly timeframe.ismonthly

timeframe.isminutes

如果当前周期是分钟周期,则返回true,否则返回false。

类型
simple bool

另见
timeframe.isdwm timeframe.isintraday timeframe.isseconds timeframe.isdaily timeframe.isweekly timeframe.ismonthly

timeframe.ismonthly

如果当前分辨率是每月分辨率,则返回true,否则返回false。

类型
simple bool

另见
timeframe.isdwm timeframe.isintraday timeframe.isminutes timeframe.isseconds timeframe.isdaily timeframe.isweekly

timeframe.isseconds

如果当前周期是秒,则返回true,否则返回false。

类型
simple bool

另见
timeframe.isdwm timeframe.isintraday timeframe.isminutes timeframe.isdaily timeframe.isweekly timeframe.ismonthly

timeframe.isweekly

如果当前分辨率是每周分辨率,则返回true,否则返回false。

类型
simple bool

另见
timeframe.isdwm timeframe.isintraday timeframe.isminutes timeframe.isseconds timeframe.isdaily timeframe.ismonthly

timeframe.multiplier

时间周期乘数,例如 '60' - 60,'D' - 1,'5D' - 5,'12M' - 12。

类型
simple int

另见
syminfo.ticker syminfo.tickerid timeframe.period

timeframe.period

时间周期。比如 '60' - 60分钟, 'D' - 日, 'W' - 周, 'M' - 月, '5D' - 5 日, '12M' - 1年, '3M' - 1个季度。

类型
simple string

另见
syminfo.ticker syminfo.tickerid timeframe.multiplier

display

display.none

一个命名常数,指定绘图的显示位置。无处显示。在警报模板消息可用。

类型
plot_display

另见
plot plotshape plotchar

display.all

一个命名常数,指定显示绘图的位置。显示任何位置。

类型
plot_display

另见
plot plotshape plotchar plotarrow plotbar plotcandle

shape

shape.xcross

plotshape功能的形状样式。

类型
const string

另见
plotshape

shape.cross

plotshape功能的形状样式。

类型
const string

另见
plotshape

shape.triangleup

plotshape功能的形状样式。

类型
const string

另见
plotshape

shape.triangledown

plotshape功能的形状样式。

类型
const string

另见
plotshape

shape.flag

plotshape功能的形状样式。

类型
const string

另见
plotshape

shape.circle

plotshape功能的形状样式。

类型
const string

另见
plotshape

shape.arrowup

plotshape功能的形状样式。

类型
const string

另见
plotshape

shape.arrowdown

plotshape功能的形状样式。

类型
const string

另见
plotshape

shape.labelup

plotshape功能的形状样式。

类型
const string

另见
plotshape

shape.labeldown

plotshape功能的形状样式。

类型
const string

另见
plotshape

shape.square

plotshape功能的形状样式。

类型
const string

另见
plotshape

shape.diamond

plotshape功能的形状样式。

类型
const string

另见
plotshape

color

color.aqua

是#00BCD4颜色的命名常量。

类型
const color

color.black

是#363A45颜色的命名常量。

类型
const color

color.blue

是#2962ff颜色的命名常量。

类型
const color

color.fuchsia

是#E040FB颜色的命名常量。

类型
const color

color.gray

是#787B86颜色的命名常量。

类型
const color

color.green

是#4CAF50颜色的命名常量。

类型
const color

color.lime

是#00E676颜色的命名常量。

类型
const color

color.maroon

为#880E4F颜色的命名常量。

类型
const color

color.navy

是#311B92颜色的命名常量。

类型
const color

color.olive

是#808000颜色的命名常量。

类型
const color

color.orange

是#FF9800颜色的命名常量。

类型
const color

color.purple

是#9C27B0颜色的命名常量。

类型
const color

color.red

是#FF5252颜色的命名常量。

类型
const color

color.silver

为#B2B5BE颜色的命名常量。

类型
const color

color.teal

color.teal

是#00897B颜色的命名常量。

类型
const color

color.white

是#FFFFFF颜色的命名常量。

类型
const color

color.yellow

是#FFEB3B颜色的命名常量。

类型
const color

plot

plot.style_line

'Line'样式的命名常量,用作plot函数中style参数的参数。

类型
plot_style

另见
plot plot.style_linebr plot.style_stepline plot.style_stepline_diamond plot.style_histogram plot.style_cross plot.style_area plot.style_areabr plot.style_columns plot.style_circles

plot.style_linebr

'Line With Breaks'样式的命名常量,用作plot函数中style参数的参数。类似于plot.style_line,除了数据中的空白没有被填充。

类型
plot_style

另见
plot plot.style_line plot.style_stepline plot.style_stepline_diamond plot.style_histogram plot.style_cross plot.style_area plot.style_areabr plot.style_columns plot.style_circles

plot.style_histogram

'Histogram'样式的命名常量,用作plot函数中style参数的参数。

类型
plot_style

另见
plot plot.style_line plot.style_linebr plot.style_stepline plot.style_stepline_diamond plot.style_cross plot.style_area plot.style_areabr plot.style_columns plot.style_circles

plot.style_columns

'Columns' 样式的命名常量,用作plot函数中的style参数的参数。

类型
plot_style

另见
plot plot.style_line plot.style_linebr plot.style_stepline plot.style_stepline_diamond plot.style_histogram plot.style_cross plot.style_area plot.style_areabr plot.style_circles

plot.style_circles

'Circles' 样式的命名常量,用作plot函数中的style参数的参数。

类型
plot_style

另见
plot plot.style_line plot.style_linebr plot.style_stepline plot.style_stepline_diamond plot.style_histogram plot.style_cross plot.style_area plot.style_areabr plot.style_columns

plot.style_area

'Area'样式的命名常量,用作plot函数中style参数的参数。

类型
plot_style

另见
plot plot.style_line plot.style_linebr plot.style_stepline plot.style_stepline_diamond plot.style_histogram plot.style_areabr plot.style_cross plot.style_columns plot.style_circles

plot.style_areabr

'Area With Breaks'样式的命名常量,用作plot函数中style参数的参数。类似于plot.style_area,除了数据中的空白没有被填充。

类型
plot_style

另见
plot plot.style_line plot.style_linebr plot.style_stepline plot.style_stepline_diamond plot.style_histogram plot.style_cross plot.style_area plot.style_columns plot.style_circles

plot.style_cross

'Cross' 样式的命名常量,用作plot函数中style参数的参数。

类型
plot_style

另见
plot plot.style_line plot.style_linebr plot.style_stepline plot.style_stepline_diamond plot.style_histogram plot.style_area plot.style_areabr plot.style_columns plot.style_circles

plot.style_stepline

'Step Line'样式的命名常量,用作plot函数中style参数的参数。

类型
plot_style

另见
plot plot.style_stepline_diamond plot.style_linebr plot.style_histogram plot.style_cross plot.style_area plot.style_areabr plot.style_columns plot.style_circles

plot.style_stepline_diamond

'Step Line With Diamonds'样式的命名常量,用作plot函数中style参数的参数。类似于plot.style_stepline,除了数据变化也用菱形标记。

类型
plot_style

另见
plot plot.style_line plot.style_linebr plot.style_histogram plot.style_cross plot.style_area plot.style_areabr plot.style_columns plot.style_circles

location

location.abovebar

location.abovebar

plotshape,plotchar功能的位置值。 形状绘制在主系列k线上方。

类型
const string

另见
plotshape plotchar location.belowbar location.top location.bottom location.absolute

location.belowbar

plotshape,plotchar功能的位置值。 形状绘制在主要系列k线下方。

类型
const string

另见
plotshape plotchar location.abovebar location.top location.bottom location.absolute

location.top

plotshape,plotchar功能的位置值。 形状绘制在顶部图表边框附近。

类型
const string

另见
plotshape plotchar location.abovebar location.belowbar location.bottom location.absolute

location.bottom

plotshape,plotchar功能的位置值。 形状绘制在底部图表边框附近。

类型
const string

另见
plotshape plotchar location.abovebar location.belowbar location.top location.absolute

location.absolute

plotshape,plotchar功能的位置值。 形状在图表上绘制,使用指标值作为价格坐标。

类型
const string

另见
plotshape plotchar location.abovebar location.belowbar location.top location.bottom

size

size.auto

size.auto

plotshape,plotchar功能的大小值。 形状的大小自动适应k线的大小。

类型
const string

另见
plotshape plotchar size.tiny size.small size.normal size.large size.huge

size.tiny

plotshape,plotchar功能的大小值。 形状的尺寸微小。

类型
const string

另见
plotshape plotchar size.auto size.small size.normal size.large size.huge

size.small

plotshape,plotchar功能的大小值。 形状的尺寸小。

类型
const string

另见
plotshape plotchar size.auto size.tiny size.normal size.large size.huge

size.normal

plotshape,plotchar功能的大小值。 形状的尺寸普通。

类型
const string

另见
plotshape plotchar size.auto size.tiny size.small size.large size.huge

size.large

plotshape,plotchar功能的大小值。 形状的尺寸大。

类型
const string

另见
plotshape plotchar size.auto size.tiny size.small size.normal size.huge

size.huge

plotshape,plotchar功能的大小值。 形状的尺寸巨大。

类型
const string

另见
plotshape plotchar size.auto size.tiny size.small size.normal size.large

alert

alert.freq_once_per_bar

与alert()函数的'freq'参数一起使用的命名常数。
K线中的第一个函数调用触发警报。

类型
const string

另见
alert

alert.freq_all

与alert()函数的'freq'参数一起使用的命名常数。
所有函数调用触发警报。

类型
const string

另见
alert

alert.freq_once_per_bar_close

与alert()函数的'freq'参数一起使用的命名常数。
该函数调用仅在实时K线的最后一个脚本迭代期间发生时,在关闭时触发警报。

类型
const string

另见
alert

format

format.inherit

是一个命名常量。

类型
const string

另见
format.price format.volume

format.price

是一个命名常量。

类型
const string

备注
如果format是format.price,则设置默认精度值。您可以使用指标函数的precision参数来更改精度值。

另见
format.inherit format.volume

format.volume

是一个命名常量。

类型
const string

另见
format.inherit format.price

syminfo

syminfo.ticker

无交易所前缀的商品代码,例如 'MSFT'。

类型
simple string

另见
syminfo.tickerid timeframe.period timeframe.multiplier

syminfo.tickerid

带有交易所前缀的商品代码,例如 “BATS:MSFT”,“NASDAQ:MSFT”。

类型
simple string

另见
syminfo.ticker timeframe.period timeframe.multiplier

syminfo.basecurrency

商品的基础货币。对于商品代码“ BTCUSD”,返回“ BTC”。

类型
simple string

另见
syminfo.currency syminfo.ticker

syminfo.currency

当前商品的货币。返回货币代码:“ USD”,“ EUR”等。

类型
simple string

另见
syminfo.basecurrency syminfo.ticker

syminfo.type

当前商品代码的类型。可能的值为stock, futures, index, forex, crypto, fund, dr。

类型
simple string

另见
syminfo.ticker

syminfo.mintick

当前品种的最小刻度值。在FMZ上,实盘/回测界面上「Pine语言交易类库」中的模板参数定价货币精度可以控制该值。定价货币精度设置2即交易时价格精确到小数点第二位,此时价格最小变动单位为0.01。syminfo.mintick的值即为0.01。

类型
simple float

另见
syminfo.pointvalue

syminfo.pointvalue

当前商品的点值

类型
simple float

另见
syminfo.mintick

syminfo.timezone

图表主要系列的交换时区。 可能的值见timestamp。

类型
simple string

另见
timestamp

barstate

barstate.islastconfirmedhistory

如果市场收盘时脚本在数据集的最后一根K线上执行,或者脚本正在实时K线之前的K线上执行,如果市场开盘,则返回true。否则返回false。

类型
series bool

备注
使用此变量的PineScript代码可以对历史记录和实时数据进行不同的计算。
请注意,使用此变量/函数可能会导致指标重新绘制。

另见
barstate.isfirst barstate.islast barstate.ishistory barstate.isrealtime barstate.isnew

barstate.isnew

如果脚本目前在新k线上计算着,则返回true,否则返回false。

类型
series bool

备注
使用此变量的PineScript代码可以对历史记录和实时数据进行不同的计算。
请注意,使用此变量/函数可能会导致指标重新绘制。

另见
barstate.isfirst barstate.islast barstate.ishistory barstate.isrealtime barstate.isconfirmed barstate.islastconfirmedhistory

barstate.isfirst

如果当前k线为k线组的第一条k线,则返回true,否则返回false。

类型
series bool

备注
使用此变量的PineScript代码可以对历史记录和实时数据进行不同的计算。
请注意,使用此变量/函数可能会导致指标重新绘制。

另见
barstate.islast barstate.ishistory barstate.isrealtime barstate.isnew barstate.isconfirmed barstate.islastconfirmedhistory

barstate.islast

如果当前k线为k线组的最后一条k线,则返回true,否则返回false。

类型
series bool

备注
使用此变量的PineScript代码可以对历史记录和实时数据进行不同的计算。
请注意,使用此变量/函数可能会导致指标重新绘制。

另见
barstate.isfirst barstate.ishistory barstate.isrealtime barstate.isnew barstate.isconfirmed barstate.islastconfirmedhistory

barstate.ishistory

如果当前k线为历史k线,则返回true,否则返回false。

类型
series bool

备注
使用此变量的PineScript代码可以对历史记录和实时数据进行不同的计算。
请注意,使用此变量/函数可能会导致指标重新绘制。

另见
barstate.isfirst barstate.islast barstate.isrealtime barstate.isnew barstate.isconfirmed barstate.islastconfirmedhistory

barstate.isconfirmed

如果脚本正在计算当前k线的最后(关闭)更新,则返回true。 下一个脚本将在新K线数据上计算。

类型
series bool

备注
使用此变量的PineScript代码可以对历史记录和实时数据进行不同的计算。
不建议在request.security表达式中使用barstate.isconfirmed。它从request.security请求的值是不可预测的。
请注意,使用此变量/函数可能会导致指标重新绘制。

另见
barstate.isfirst barstate.islast barstate.ishistory barstate.isrealtime barstate.isnew barstate.islastconfirmedhistory

barstate.isrealtime

如果当前k线为实时k线,则返回true,否则返回false。

类型
series bool

备注
使用此变量的PineScript代码可以对历史记录和实时数据进行不同的计算。
请注意,使用此变量/函数可能会导致指标重新绘制。

另见
barstate.isfirst barstate.islast barstate.ishistory barstate.isnew barstate.isconfirmed barstate.islastconfirmedhistory

barstate.time

暂无

ta

ta.accdist

累积/分布指数

类型
series float

ta.iii

盘中强度指数。

类型
series float

例子

// Intraday Intensity Index
plot(ta.iii, color=color.yellow)

// the same on pine
f_iii() =>
    (2 * close - high - low) / ((high - low) * volume)

plot(f_iii())

ta.nvi

负量指标。

类型
series float

例子

// Negative Volume Index

plot(ta.nvi, color=color.yellow)

// the same on pine
f_nvi() =>
    float ta_nvi = 1.0
    float prevNvi = (nz(ta_nvi[1], 0.0) == 0.0)  ? 1.0: ta_nvi[1]
    if nz(close, 0.0) == 0.0 or nz(close[1], 0.0) == 0.0
        ta_nvi := prevNvi
    else
        ta_nvi := (volume < nz(volume[1], 0.0)) ? prevNvi + ((close - close[1]) / close[1]) * prevNvi : prevNvi
    result = ta_nvi

plot(f_nvi())

ta.pvi

正量指标。

类型
series float

例子

// Positive Volume Index

plot(ta.pvi, color=color.yellow)

// the same on pine
f_pvi() =>
    float ta_pvi = 1.0
    float prevPvi = (nz(ta_pvi[1], 0.0) == 0.0)  ? 1.0: ta_pvi[1]
    if nz(close, 0.0) == 0.0 or nz(close[1], 0.0) == 0.0
        ta_pvi := prevPvi
    else
        ta_pvi := (volume > nz(volume[1], 0.0)) ? prevPvi + ((close - close[1]) / close[1]) * prevPvi : prevPvi
    result = ta_pvi

plot(f_pvi())

ta.obv

能量潮指标。

类型
series float

例子

// On Balance Volume
plot(ta.obv, color=color.yellow)

// the same on pine
f_obv() =>
    ta.cum(math.sign(ta.change(close)) * volume)

plot(f_obv())

ta.pvt

价量趋势指标。

类型
series float

例子

// Price-Volume Trend
plot(ta.pvt, color=color.yellow)

// the same on pine
f_pvt() =>
    ta.cum((ta.change(close) / close[1]) * volume)

plot(f_pvt())

ta.wad

威廉多空力度线。

类型
series float

例子

// Williams Accumulation/Distribution
plot(ta.wad, color=color.yellow)

// the same on pine
f_wad() =>
    trueHigh = math.max(high, close[1])
    trueLow = math.min(low, close[1])
    mom = ta.change(close)
    gain = (mom > 0) ? close - trueLow : (mom < 0) ? close - trueHigh : 0
    ta.cum(gain)

plot(f_wad())

ta.wvad

威廉变异离散量。

类型
series float

例子

// Williams Variable Accumulation/Distribution
plot(ta.wvad, color=color.yellow)

// the same on pine
f_wvad() =>
    (close - open) / (high - low) * volume

plot(f_wvad())

math

math.e

是欧拉数的命名常数。它等于2.7182818284590452。

类型
const float

另见
math.phi math.pi math.rphi

math.phi

是黄金分割的命名常数。等于1.6180339887498948。

类型
const float

另见
math.e math.pi math.rphi

math.pi

是阿基米德常数的命名常数。它等于3.1415926535897932。

类型
const float

另见
math.e math.phi math.rphi

math.rphi

是黄金分割率的命名常数。它等于0.6180339887498948。

类型
const float

另见
math.e math.pi math.phi

strategy

strategy.equity

当前权益(strategy.initial_capital + strategy.netprofit + strategy.openprofit)。

类型
series float

另见
strategy.netprofit strategy.openprofit strategy.position_size

strategy.position_size

目前市场头寸的方向和规模。 如果值> 0,则市场头寸较长。 如果值<0,则市场头寸较短。 绝对值是交易中的合同/股/手/单位数(头寸大小)。

类型
series float

另见
strategy.position_avg_price

strategy.position_avg_price

当前市场定位平均入场价。 如果市场地位平滑,则“NaN”就会退回。

说明
FMZ PINE Script中的均价均为包含手续费的价格。例如:下单价格为8000,卖出方向,数量1手(个、张),成交后均价不是8000,低于8000(成本中包含了手续费)。

类型
series float

另见
strategy.position_size

strategy.long

多头方向。

类型
strategy_direction

另见
strategy.entry strategy.exit

strategy.short

空头方向。

类型
strategy_direction

另见
strategy.entry strategy.exit

strategy.closedtrades

在整个交易间隔内被关闭的交易数量。

类型
series int

另见
strategy.position_size strategy.opentrades

strategy.opentrades

未关闭或者继续持有的交易数量。如果没有,则显示0。

类型
series int

另见
strategy.position_size

strategy.netprofit

所有已完成交易的总货币价值。

类型
series float

另见
strategy.openprofit strategy.position_size strategy.grossprofit

strategy.grossprofit

所有已完成赢利交易的总货币价值。

类型
series float

另见
strategy.netprofit

strategy.openprofit

当前未结仓位的未实现损益。

类型
series float

另见
strategy.netprofit strategy.position_size

strategy.direction.long

只能做多的策略

类型
const string

另见
strategy.risk.allow_entry_in

strategy.direction.short

只能做空的策略

类型
const string

另见
strategy.risk.allow_entry_in

strategy.direction.all

允许既可以做多又可以做空的策略

类型
const string

另见
strategy.risk.allow_entry_in

dayofweek

dayofweek

交换时区的当前k线时间的星期。

类型
series int

备注
请注意,此变量根据K线的打开时间返回天。对于隔夜交易时段(例如EURUSD,其周一交易时段从周日17:00开始),该值可以比交易日的天低1。
您可以使用dayofweek.sunday,dayofweek.monday,dayofweek.tuesday,dayofweek.wednesday,dayofweek.thursday,dayofweek.friday和dayofweek.saturday变量用于比较。

另见
time dayofmonth

dayofweek.sunday

是dayofweek函数的返回值和dayofweek变量的值的命名常量。

类型
const int

另见
dayofweek.monday dayofweek.tuesday dayofweek.wednesday dayofweek.thursday dayofweek.friday dayofweek.saturday

dayofweek.monday

是dayofweek函数的返回值和dayofweek变量的值的命名常量。

类型
const int

另见
dayofweek.sunday dayofweek.tuesday dayofweek.wednesday dayofweek.thursday dayofweek.friday dayofweek.saturday

dayofweek.tuesday

是dayofweek函数的返回值和dayofweek变量的值的命名常量。

类型
const int

另见
dayofweek.sunday dayofweek.monday dayofweek.wednesday dayofweek.thursday dayofweek.friday dayofweek.saturday

dayofweek.wednesday

是dayofweek函数的返回值和dayofweek变量的值的命名常量。

类型
const int

另见
dayofweek.sunday dayofweek.monday dayofweek.tuesday dayofweek.thursday dayofweek.friday dayofweek.saturday

dayofweek.thursday

是dayofweek函数的返回值和dayofweek变量的值的命名常量。

类型
const int

另见
dayofweek.sunday dayofweek.monday dayofweek.tuesday dayofweek.wednesday dayofweek.friday dayofweek.saturday

dayofweek.friday

是dayofweek函数的返回值和dayofweek变量的值的命名常量。

类型
const int

另见
dayofweek.sunday dayofweek.monday dayofweek.tuesday dayofweek.wednesday dayofweek.thursday dayofweek.saturday

dayofweek.saturday

是dayofweek函数的返回值和dayofweek变量的值的命名常量。

类型
const int

另见
dayofweek.sunday dayofweek.monday dayofweek.tuesday dayofweek.wednesday dayofweek.thursday dayofweek.friday

hline

hline.style_dashed

是Hline函数的点划线样式的命名常量。

类型
hline_style

另见
hline.style_solid hline.style_dotted

hline.style_dotted

hline.style_dotted

是Hline函数的点虚线样式的命名常量。

类型
hline_style

另见
hline.style_solid hline.style_dashed

hline.style_solid

是Hline函数的实心线型的命名常量。

类型
hline_style

另见
hline.style_dotted hline.style_dashed

barmerge

barmerge.gaps_on

给所请求的数据合并策略。 数据与可能的差距(na值)合并。

类型
barmerge_gaps

另见
request.security barmerge.gaps_off

barmerge.gaps_off

合并所请求数据的策略。 数据不间断地合并,所有的差距都以先前最近的现有值填满。

类型
barmerge_gaps

另见
request.security barmerge.gaps_on

barmerge.lookahead_on

合并所请求数据位置的策略。 请求的条形图与当前的条形图按照k线开盘时间合并。 这种合并策略可能导致从“未来”获取数据计算历史的不良影响。 这在回溯测试策略中不被接受,但在指标中可使用。

类型
barmerge_lookahead

另见
request.security barmerge.lookahead_off

barmerge.lookahead_off

合并所请求数据位置的策略。 所请求的条形图与当前的条形图按照k线收盘时间合并。 这种合并策略禁止从“未来”获取数据计算历史的影响。

类型
barmerge_lookahead

另见
request.security barmerge.lookahead_on

others

hl2

是(最高价 + 最低价)/2的快捷键

类型
series float

另见
open high low close volume time hlc3 hlcc4 ohlc4

hlc3

是(最高价+最低价+收盘价)/3的快捷键

类型
series float

另见
open high low close volume time hl2 hlcc4 ohlc4

hlcc4

是(高+低+收+收)/4的快捷键

类型
series float

另见
open high low close volume time hl2 hlc3 ohlc4

ohlc4

是(开盘价 + 最高价 + 最低价 + 收盘价)/4的快捷键

类型
series float

另见
open high low close volume time hl2 hlc3 hlcc4

na

Double.NaN值 (非数字)。

类型
simple na

例子

// na
plot(bar_index < 10 ? na : close)    // CORRECT
plot(close == na ? close[1] : close)    // INCORRECT!
plot(na(close) ? close[1] : close)    // CORRECT

备注
仅用于返回值。 别试图与它比较! 如果您要检查某些值是否为NaN,请使用内置函数na。

另见
na

bar_index

目前的价格棒指数。 编号从零开始,第一个条的索引为0。

类型
series int

例子

// bar_index
plot(bar_index)
plot(bar_index > 5000 ? close : 0)

备注
请注意, bar_index 已替换版本4中的 n 变量。
请注意,K线索引从第一根历史K线起算为0。
请注意,使用此变量/函数可能会导致指标重新绘制。

另见
barstate.isfirst barstate.islast barstate.isrealtime

last_bar_index

最后一根图表K线的索引。K线索引以第一根K线为零开始。

类型
series int

例子

strategy("Mark Last X Bars For Backtesting", overlay = true, calc_on_every_tick = true)
lastBarsFilterInput = input.int(100, "Bars Count:")
// Here, we store the 'last_bar_index' value that is known from the beginning of the script's calculation.
// The 'last_bar_index' will change when new real-time bars appear, so we declare 'lastbar' with the 'var' keyword.
var lastbar = last_bar_index
// Check if the current bar_index is 'lastBarsFilterInput' removed from the last bar on the chart, or the chart is traded in real-time.
allowedToTrade = (lastbar - bar_index <= lastBarsFilterInput) or barstate.isrealtime
bgcolor(allowedToTrade ? color.new(color.green, 80) : na)

返回值
收盘的最后历史K线索引,或开盘的实时K线索引。

备注
请注意,使用此变量可能会导致指标重绘。

另见
bar_index last_bar_time barstate.ishistory barstate.isrealtime

time

UNIX格式的当前k线时间。 这是自1970年1月1日00:00:00 UTC以来的毫秒数。

timenow

UNIX格式的当前时间。 这是自1970年1月1日00:00:00 UTC以来的毫秒数。

类型
series int

备注
请注意,使用此变量/函数可能会导致指标重新绘制。

另见
timestamp time dayofmonth dayofweek

类型
series int

备注
请注意,此变量将根据K线的打开时间返回时间戳。因此,对于隔夜交易时段(例如EURUSD,其周一时段从周日17:00开始),此变量可以返回交易日指定日期之前的时间。例如,在EURUSD上,“dayofmonth(time)”可以比交易日的日期低1,因为当前日期的K线实际上是前一天打开的。

另见
time dayofmonth dayofweek

year

交换时区的当前年k线。

类型
series int

备注
请注意,此变量根据K线的打开时间返回年份。对于隔夜交易时段(例如EURUSD,其周一交易时段从周日17:00开始),该值可以比交易日的年份低1。

另见
year time month weekofyear dayofmonth dayofweek hour minute second

month

交易所时区的当前月k线。

类型
series int

备注
请注意,此变量根据K线的打开时间返回月份。对于隔夜交易时段(例如EURUSD,其周一交易时段从周日17:00开始),该值可以比交易日的月份低1。

另见
month time year weekofyear dayofmonth dayofweek hour minute second

hour

交易所时区的当前小时k线。

类型
series int

另见
hour time year month weekofyear dayofmonth dayofweek minute second

minute

交易所时区的当前分钟k线。

类型
series int

另见
minute time year month weekofyear dayofmonth dayofweek hour second

second

交易所时区的当前秒k线。

类型
series int

另见
second time year month weekofyear dayofmonth dayofweek hour minute

open

当前开盘价。

类型
series float

备注
可使用方括号运算符 []来访问以前的值,例如。 open[1],open[2]。

另见
high low close volume time hl2 hlc3 hlcc4 ohlc4

high

当前最高价。

类型
series float

备注
可使用方括号运算符 []来访问以前的值,例如。 high[1],high[2]。

另见
open low close volume time hl2 hlc3 hlcc4 ohlc4

low

当前最低价。

类型
series float

备注
可使用方括号运算符 []来访问以前的值,例如。 low[1],low[2]。

另见
open high close volume time hl2 hlc3 hlcc4 ohlc4

close

当前K线关闭时的收盘价,或尚未完成的实时K线的最后交易价格。

类型
series float

备注
可使用方括号运算符 []来访问以前的值,例如。 close[1],close[2]。

另见
open high low volume time hl2 hlc3 hlcc4 ohlc4

volume

当前K线成交量。

类型
series float

备注
可使用方括号运算符 []来访问以前的值,例如。 volume[1],volume[2]。

另见
open high low close time hl2 hlc3 hlcc4 ohlc4

weekofyear

交换时区的当前k线时段的周数。

类型
series int

备注
请注意,此变量根据K线的打开时间返回周。对于隔夜交易时段(例如EURUSD,其周一交易时段从周日17:00开始),该值可以比交易日的周低1。

另见
weekofyear time year month dayofmonth dayofweek hour minute second

dayofmonth

交换时区的当前k线时间的日期。

类型
series int

备注
请注意,此变量根据K线的打开时间返回天。对于隔夜交易时段(例如EURUSD,其周一交易时段从周日17:00开始),该值可以比交易日的天低1。

另见
time dayofweek

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
flot 中文api2
一篇文章带你使用Pandas画出图形
Python数据可视化——matplotlib使用
【原创】用python开发股票自动技术分析的软件(四)
【声学案例】02:FWH方法(续)
Python Pandas学习之Pandas数据结构详解
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服