Chuyển đến nội dung chính
ATK Pine Script®

Tham chiếu các hàm Collection

Tham chiếu cho các namespace array.*, map.*, và matrix.* trong ATK PyneScript V6 — rolling buffer, keyed runtime bundle, và lưới số 2D.

Namespace array.*#

Namespace array cung cấp một container kiểu danh sách theo phong cách Pine. Ngoài các helper thay đổi dữ liệu cốt lõi (push, pop, get, set, size), nó còn bao gồm các phương thức tổng hợp và sắp xếp lại để tóm tắt hoặc tái cấu trúc danh sách đã lưu.

Các phương thức tổng hợp#

Phương thứcTrả vềSử dụng khi
array.first(handle)Phần tử đầu tiên, hoặc NoneBạn muốn phần tử cũ nhất mà không cần pop.
array.last(handle)Phần tử cuối cùng, hoặc NoneBạn muốn phần tử mới nhất mà không cần slice toàn bộ.
array.sum(handle)floatTổng cộng dồn của một buffer số.
array.avg(handle)floatTrung bình của một buffer số; các giá trị NaN được loại trừ.
array.min(handle)floatGiá trị nhỏ nhất trong tất cả phần tử; an toàn với NaN.
array.max(handle)floatGiá trị lớn nhất trong tất cả phần tử; an toàn với NaN.
array.sort(handle, order="asc")None (tại chỗ)Sắp xếp buffer trước khi đọc giá trị theo thứ hạng.
array.reverse(handle)None (tại chỗ)Đảo ngược thứ tự hiện tại.
array.fill(handle, value, index_from=0, index_to=None)None (tại chỗ)Đặt lại một dải phần tử về hằng số mà không cần xây dựng lại array.

Rolling Buffer với đọc tổng hợp#

from source import array, indicator, ta

indicator("Rolling Buffer Demo", overlay=False)

buf = array.new_float(0)

def build_indicator_frame(df, params=None):
    frame = df.copy().reset_index(drop=True)
    for val in frame["close"].tolist():
        array.push(buf, float(val))
        if array.size(buf) > 20:
            array.shift(buf)   # keep last 20 values

    frame["buf_avg"]   = array.avg(buf)
    frame["buf_min"]   = array.min(buf)
    frame["buf_max"]   = array.max(buf)
    frame["buf_sum"]   = array.sum(buf)
    frame["buf_first"] = array.first(buf)
    frame["buf_last"]  = array.last(buf)
    return frame

Sort, Reverse, và Fill#

# Sort ascending then read the median element.
scores = array.from_([5.0, 1.0, 3.0, 4.0, 2.0])
array.sort(scores, order="asc")
median_value = array.get(scores, array.size(scores) // 2)

# Fill a buffer with zeros to reset it.
data = array.new_float(10, 0.0)
array.fill(data, 0.0)

Namespace map.*#

Namespace map cung cấp một container từ điển có khóa string với API ổn định theo phong cách Pine. Sử dụng khi bạn cần lưu trữ metadata key-value trong phạm vi script cùng với frame, truyền parameter có tên giữa các helper, hoặc ghi cấu hình theo lượt chạy trong frame.attrs.

Phương thứcTrả vềGhi chú
map.new()map handle {}Tạo một map rỗng. Thường gán cho biến cấp module.
map.put(handle, key, value)NoneChèn hoặc ghi đè một key.
map.get(handle, key, default=None)giá trị đã lưu hoặc defaultĐọc an toàn; trả về default khi key không tồn tại.
map.keys(handle)list[str]Tất cả các key hiện tại. Hữu ích cho lặp hoặc kiểm tra nội dung.
map.values(handle)listTất cả các giá trị hiện tại theo thứ tự chèn.
map.size(handle)intSố lượng entry.
map.contains(handle, key)boolKiểm tra xem key có tồn tại trước khi gọi get.
map.remove(handle, key)NoneXóa một key nếu tồn tại.
map.clear(handle)NoneXóa tất cả entry.
map.copy(handle)map handle mớiBản sao nông. Phù hợp để snapshot trước khi thay đổi.
map.to_array_keys(handle)list[str]Bản sao độc lập của tất cả key dưới dạng danh sách thuần.
map.to_array_values(handle)listBản sao độc lập của tất cả giá trị dưới dạng danh sách thuần.

map.* trong Frame Builder#

from source import indicator, input, map, ta

indicator("Map Runtime Demo", overlay=False)
fast_length = input.int(8,  title="Fast", key="fast_length")
slow_length = input.int(21, title="Slow", key="slow_length")


def build_indicator_frame(df, params=None):
    frame = df.copy().reset_index(drop=True)
    merged = {"fast_length": int(fast_length), "slow_length": int(slow_length)} | dict(params or {})

    fast = max(int(merged.get("fast_length", 8)  or 8),  1)
    slow = max(int(merged.get("slow_length", 21) or 21), 1)

    frame["ema_fast"]     = ta.ema(frame["close"], fast)
    frame["ema_slow"]     = ta.ema(frame["close"], slow)
    frame["spread_value"] = (frame["ema_fast"] - frame["ema_slow"]).fillna(0.0)

    cfg = map.new()
    map.put(cfg, "fast_length", fast)
    map.put(cfg, "slow_length", slow)
    trend = "bullish" if float(frame["spread_value"].iloc[-1] or 0.0) >= 0.0 else "bearish"
    map.put(cfg, "trend_bias", trend)

    frame.attrs["map_keys"]    = map.keys(cfg)
    frame.attrs["map_size"]    = map.size(cfg)
    frame.attrs["trend_bias"]  = map.get(cfg, "trend_bias", "neutral")
    return frame

Khi nào dùng map vs dict: dùng map.* khi viết theo phong cách PyneScript và map sẽ được truyền cho các helper PyneScript khác. Dùng dict thuần Python khi dữ liệu chỉ nằm nội bộ trong một function duy nhất và không bao giờ vượt qua ranh giới API phong cách Pine.

Tải ví dụ map runtime


Namespace matrix.*#

Namespace matrix mô hình hóa một lưới số 2 chiều. Sử dụng khi bạn cần lưu một cửa sổ dữ liệu bar đa cột, tính toán bề mặt hiệp phương sai dồn, hoặc truyền payload số có cấu trúc giữa các giai đoạn.

Phương thứcTrả vềGhi chú
matrix.new(rows, cols, fill=0.0)matrix handleTạo lưới rows x cols được điền sẵn với fill.
matrix.set(handle, row, col, value)NoneGhi một ô đơn.
matrix.get(handle, row, col)floatĐọc một ô đơn.
matrix.rows(handle)intSố hàng hiện tại.
matrix.columns(handle)intSố cột hiện tại.
matrix.row(handle, row_index)list[float]Tất cả giá trị trong một hàng cụ thể.
matrix.col(handle, col_index)list[float]Tất cả giá trị trong một cột cụ thể.
matrix.add_row(handle, row_index, values)NoneChèn một hàng mới tại một vị trí.
matrix.add_col(handle, values)NoneThêm một cột mới vào cuối.
matrix.remove_row(handle, row_index)NoneXóa một hàng.
matrix.submatrix(handle, from_row, to_row, from_col, to_col)matrix handle mớiTrích xuất một lát cắt hình chữ nhật thành matrix mới.
matrix.sum(handle)floatTổng tất cả phần tử không phải NaN.
matrix.avg(handle)floatTrung bình tất cả phần tử không phải NaN.
matrix.min(handle)floatPhần tử nhỏ nhất (an toàn với NaN).
matrix.max(handle)floatPhần tử lớn nhất (an toàn với NaN).
matrix.copy(handle)matrix handle mớiBản sao sâu. An toàn để thay đổi độc lập.

Ví dụ cửa sổ OHLC#

from source import indicator, input, matrix

indicator("Matrix Runtime Demo", overlay=False)
window = input.int(3, title="Window", key="window", minval=1)


def build_indicator_frame(df, params=None):
    frame = df.copy().reset_index(drop=True)
    merged = {"window": int(window)} | dict(params or {})
    win = max(int(merged.get("window", 3) or 3), 1)

    tail = frame.tail(win).reset_index(drop=True)
    grid = matrix.new(len(tail), 2, 0.0)

    for i, row in tail.iterrows():
        matrix.set(grid, i, 0, float(row["open"]))
        matrix.set(grid, i, 1, float(row["close"]))

    # Append a computed column: high-low range.
    matrix.add_col(grid, values=(tail["high"] - tail["low"]).astype(float).tolist())

    frame["open_sum"]       = float(sum(matrix.col(grid, 0))) if matrix.rows(grid) > 0 else 0.0
    frame["close_sum"]      = float(sum(matrix.col(grid, 1))) if matrix.rows(grid) > 0 else 0.0
    frame["range_sum"]      = float(sum(matrix.col(grid, 2))) if matrix.rows(grid) > 0 else 0.0
    frame["grid_total_sum"] = matrix.sum(grid)
    frame["grid_avg"]       = matrix.avg(grid)

    frame.attrs["matrix_shape"] = {"rows": matrix.rows(grid), "columns": matrix.columns(grid)}
    frame.attrs["last_row"]     = matrix.row(grid, matrix.rows(grid) - 1) if matrix.rows(grid) > 0 else []
    return frame

Trích xuất Submatrix#

# Extract top-left 2×2 sub-grid from a 4×4 matrix.
full = matrix.new(4, 4, 1.0)
sub  = matrix.submatrix(full, from_row=0, to_row=2, from_col=0, to_col=2)
print(matrix.rows(sub), matrix.columns(sub))  # 2, 2

Tải ví dụ matrix runtime

Xem thêm: