我們為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的腳本範例:



要了解最新的Pine Script®功能,請關注用戶手冊的發行說明。 PineCoders帳戶透過Telegram上的Squawk Box、Twitter帳戶以及TradingView上的Pine Script® Q&A公共聊天室更新。
我們希望您發現這個功能很實用,並且請繼續向我們發送您的反饋和建議,以便我們能夠使該平台成為最好的。我們為您建構TradingView,我們始終渴望聽到您的想法。
— TradingView團隊