我们为Pine编码人员提供了一个新工具 — Map,以键值对形式保存数据的集合。 它们允许用户将不同类型的相关元素链接在一起,以便稍后在脚本中访问。与其它Pine集合不同,脚本使用键值对中的键(而不是内部索引)快速访问map的值。
map命名空间是我们所有与map相关的函数的所在地。要创建map,请使用map.new<key_type, value_type>()函数。 例如:
//@variable A map containing `int` keys and `line` values. m = map.new<int, line>()
Map的键可以是任何基本类型(int,float,bool,string或color),其值可以是任何类型,甚至是用户定义的类型。
创建map后,您可以使用map命名空间中的任何函数。例如,您可以使用map.put()将键值对放入其中,并使用 map.get()检索链接到唯一键的值。您还可以使用map.keys()或map.values()从所有map的键或值生成一个数组。有关使用这些新集合及其相关功能的更多信息,请参阅我们的map用户手册页面。
在下面的示例中,我们创建了一个脚本,该脚本使用map在交易时段价格变化时为图表的背景着色。它使用data map来存储每日交易时段的收盘时间和净价格变化信息,然后计算当前交易时段的价格变化与指定数量的历史会话的平均变化的比率。它使用colors map的内容根据该比率为图表背景着色,并在数据窗口中显示比率的值:
//@version=5 indicator("Session change highlighter", overlay = true) // Inputs sessionInput = input.session("0800-1700", "Session") timezone = input.string("America/New_York", "Timezone") length = input.int(10, "Sessions to compare") //@variable A map of `int` closing time keys and `float` price change values. var data = map.new<int, float>() //@variable A map of `string` keys and `color` values for calculating the `highlightColor`. var colors = map.new<string, color>() var float sessionOpen = na float relativeChange = na int closeTime = time_close("D", sessionInput, timezone) // Put (`string`, `color`) pairs into the `colors` map on the first bar. if barstate.isfirst colors.put("Purple", color.new(color.purple, 50)) colors.put("Orange", color.new(color.orange, 50)) colors.put("Yellow", color.new(color.yellow, 50)) if not na(closeTime) // Update the session's opening price. if na(closeTime[1]) sessionOpen := open // Assign a new value to the `closeTime` key in the `data` map. data.put(closeTime, math.abs(close - sessionOpen) / sessionOpen) //@variable An `array` of price changes from each session in the `data` map. sessionHistory = data.values() //@variable The number of sessions included in the `data` map. dataSize = data.size() if dataSize >= length //@variable The average price change over `length` sessions. avgSessionChange = sessionHistory.slice(dataSize - length, dataSize).avg() relativeChange := data.get(closeTime) / avgSessionChange //@variable Returns a color gradient based on the `relativeChange` using the values in the `colors` map. highlightColor = switch relativeChange <= 1 => color.from_gradient(relativeChange, 0, 1, colors.get("Purple"), colors.get("Orange")) => color.from_gradient(relativeChange, 1, 2, colors.get("Orange"), colors.get("Yellow")) bgcolor(highlightColor, title = "Background highlight") plot(relativeChange, "Relative Change Ratio", highlightColor, display = display.data_window)
以下出版物是使用map的脚本示例:
由SamRecio提供的Volume/Market Profile
由Trendoscope提供的Historical Pattern Matcher
要了解最新的Pine Script®功能,请关注用户手册的发行说明。PineCoders帐户还通过Telegram上的Squawk Box、Twitter帐户以及TradingView上的Pine Script® Q&A公共聊天广播更新。
我们希望您发现这个备受期待的功能像我们认为的那样有用,并请继续向我们发送您的反馈和建议,以便我们成为最好的平台。我们为您打造TradingView,始终渴望听到您的想法。
— TradingView团队
还没有关注我们的中文微信公众号?快来扫二维码吧!