ThinkScript 到 PineScript 的转换问题

问题描述

我正在将 ThinkScript 指标转换为 Pinescript。我目前在将 ThinkScript 的 barNumber() 函数转换为 Pinescript 时遇到问题。我想我知道使用什么作为它的等价物,但即使在阅读了文档和示例之后,我也不确定我是否理解 barNumber()。

该指标基本上用作进场/出场指标。我认为代码使用 barNumber() 所做的是在绘制新信号时删除信号,但如果该新信号无效,则它会恢复为之前的信号。

这是我对前几个 defs 后面有更多内容感到困惑的代码部分,只是解释它们无关紧要,它们都应该作为浮点数返回(def stateUp 到 def linDev):

def bar = barNumber();

def stateUp;
def statedn;
def atrCCI;
def price;
def linDev;

def CCI = if linDev == 0 
  then 0 
else (price - avg(price,length)) / linDev / 0.05;

def MT1 = if CCI > 0
  then max(MT1[1],hl2 - ATRCCI)
else (min(MT1[1],hl2 + ATRCCI)

def state = if close > ST and close > MT1 then StateUp
else if close < ST and close < MT1 then Statedn
else State[1];

def newState = HighestAll(if state <> state[1] then bar else 0);

这段代码使用了很多条件语句,下面是这段代码的一些其他用法

CSA = if bar >= newState then MT1 else Double.NaN;

signal = if bar >= newState and state == stateUp and. . .

在 Pinescript 中是否有一种简单的方法可以解决这个问题?

感谢您的帮助!

解决方法

thinkScript 的 BarNumber() 相当于 Pine-Script 的 bar_index


thinkScript 和 Pine-Script 都使用一个循环来表示有效的交易周期范围。 BarNumber/bar_index 值表示通过循环计算的每个测量周期。

为了将其与其他类型的编码进行比较,您可以考虑在 10 天的交易期内使用 for bar_index in 0 to 10 之类的东西,其中 bar_index 将从 0 计数到 9(即,它的作用类似于典型的ifor 循环中)。

指数代表的时间段可以是一天、一分钟、刻度等 - 无论您为图表或计算设置什么。并且,请注意:*“天”代表“交易日”,不是“日历日”。

一个令人困惑的问题是:条形从哪里开始计数? BarNumber() 或 bar_index 从您时间范围的最早时间段开始,并向上计入您时间范围内的最近交易时间段。例如, bar_index 为 0 可能代表 10 天前,而 bar_index 为 9 可能代表今天。

以下是来自 Kodify site (which provides Pine-Script tutorials) 的一些示例代码:

//@version=4
study("Example of bar_index variable",overlay=true)

// Make a new label once
var label myLabel = label.new(x=bar_index,y=high + tr,textcolor=color.white,color=color.blue)

// On the last bar,show the chart's bar count
if (barstate.islast)
    // Set the label content
    label.set_text(id=myLabel,text="Bars on\nthe chart:\n" +
         tostring(bar_index + 1))

    // Update the label's location
    label.set_x(id=myLabel,x=bar_index)
    label.set_y(id=myLabel,y=high + tr)

注意 tostring(bar_index + 1))。他们加一是因为,请记住,索引是从零开始的,所以从 0 到 9 计数的索引实际上是在计数 10 根柱线。


我认为 BarNumber()/bar_index 概念令人困惑的原因是因为我们也以另一种方式考虑值。例如,如果我们将 closeclose[1] 进行比较,即当前时段的 close 值与前一时段的 close 值 (close[1]) 相比。这与小节数相反close[1] 实际上会有一个较低的柱形编号/索引,因为它来自于之前 close

当我们使用 close[1] 之类的东西时,脚本实际上是从右到左计数(最近到较早的时期)——与 BarNumber()/bar_index 概念相反。