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ức | Trả về | Sử dụng khi |
|---|---|---|
array.first(handle) | Phần tử đầu tiên, hoặc None | Bạ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 None | Bạn muốn phần tử mới nhất mà không cần slice toàn bộ. |
array.sum(handle) | float | Tổng cộng dồn của một buffer số. |
array.avg(handle) | float | Trung bình của một buffer số; các giá trị NaN được loại trừ. |
array.min(handle) | float | Giá trị nhỏ nhất trong tất cả phần tử; an toàn với NaN. |
array.max(handle) | float | Giá 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 frameSort, 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ức | Trả 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) | None | Chè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) | list | Tất cả các giá trị hiện tại theo thứ tự chèn. |
map.size(handle) | int | Số lượng entry. |
map.contains(handle, key) | bool | Kiểm tra xem key có tồn tại trước khi gọi get. |
map.remove(handle, key) | None | Xóa một key nếu tồn tại. |
map.clear(handle) | None | Xóa tất cả entry. |
map.copy(handle) | map handle mới | Bả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) | list | Bả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 frameKhi 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.
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ức | Trả về | Ghi chú |
|---|---|---|
matrix.new(rows, cols, fill=0.0) | matrix handle | Tạo lưới rows x cols được điền sẵn với fill. |
matrix.set(handle, row, col, value) | None | Ghi một ô đơn. |
matrix.get(handle, row, col) | float | Đọc một ô đơn. |
matrix.rows(handle) | int | Số hàng hiện tại. |
matrix.columns(handle) | int | Số 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) | None | Chèn một hàng mới tại một vị trí. |
matrix.add_col(handle, values) | None | Thêm một cột mới vào cuối. |
matrix.remove_row(handle, row_index) | None | Xóa một hàng. |
matrix.submatrix(handle, from_row, to_row, from_col, to_col) | matrix handle mới | Trích xuất một lát cắt hình chữ nhật thành matrix mới. |
matrix.sum(handle) | float | Tổng tất cả phần tử không phải NaN. |
matrix.avg(handle) | float | Trung bình tất cả phần tử không phải NaN. |
matrix.min(handle) | float | Phần tử nhỏ nhất (an toàn với NaN). |
matrix.max(handle) | float | Phần tử lớn nhất (an toàn với NaN). |
matrix.copy(handle) | matrix handle mới | Bả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 frameTrí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, 2Xem thêm: