Quanta Docs
·Tài liệu Quanta hoàn chỉnh cho Quant Studio
Wiki Quanta
Phân loại theo lộ trình học. Bài mẫu và ví dụ nằm riêng — không lẫn với khái niệm.
Nền tảng (5)
Quanta là gì?
DSL bậc cao chuyên cho algo/quant trading: ngắn, rõ, indent-aware, sandbox-safe, chạy chung 1 codebase cho backtest/paper/live.
Cấu trúc các block của một chiến lược
Mỗi script gồm header (strategy/study/screener) + 4 block: inputs/params, logics/..., act, render/plots. Có thêm `risk:`, các block tự do và `fn` UDF tuỳ chọn.
Kiểu dữ liệu
Series, scalar (int/float/bool), string, dict (struct return của bbands/macd), enum bareword (cyan, arrow_up).
Khối `inputs:` — tham số user-tunable
Khai báo tham số có default, optional type hint và range hint cho UI slider.
Metadata header strategy — @regime, @style, @detail (+ tuỳ chọn watchlist/timeframe)
Annotation dưới header `strategy` cho Chợ AI CIO. AI codegen bắt buộc @regime/@style/@detail (chuỗi); watchlist/timeframe tuỳ chọn (chuỗi, tách bằng dấu phẩy).
Cú pháp (7)
Story expressions — cross, rising, get when, barssince
Trong block compute, viết infix/postfix thay gọi hàm: `a crossover b`, `x rising for 3 bars`, `get x when cond`.
Lookback `x[k]` — luôn k ≥ 0
x[1] = bar trước; x[2] = 2 bar trước. CẤM `x[-k]` (lookahead — semcheck reject).
Khối `when cond:` / `if cond:` — phản ứng theo bar
Tương đương `if last_bar(cond):` — body chạy khi điều kiện ở bar mới nhất là True. `if` là alias của `when`. Hover `when` → docs `iif`.
Pipe `|>` — Pipe Operator
`x |> f(args)` ≡ `f(x, args)`.Toán tử Pipe, chuỗi nhiều bước smoothing/filter, Code trông sạch hơn thay vì viết cách lồng hàm truyền thống
Toán tử & ternary
Số học `+ − * / % **`, gán `+= -= ++ --`, so sánh `== != < <= > >=`, bool `and / or / not`, ternary `cond ? a : b` / `a when cond else b`.
Hàm tự định nghĩa `fn`
Khai báo helper tái sử dụng — tránh lặp code. Có default value cho param.
Pattern: cross của 2 series
`crossover(a, b)` chuẩn AFL/Pine — bool series, chỉ True ở bar vừa cắt.
Namespace (5)
Namespace `market.*`
Ticker frame đầy đủ — OHLCV, time, index, last, symbol(). Alias: bar.*, tape.*.
Namespace `bar.*`
Alias đầy đủ của ticker frame — giống hệt market.* và tape.*.
Namespace `tape.*`
Alias đầy đủ của ticker frame — giống hệt market.* và bar.*.
Namespace `position.*`
is_hold, is_long, is_short, qty, wnav, cost_price, pnl, nav.
Namespace `account.*`
nav, cash, exposure — trạng thái portfolio paper/live.
Khối Render (16)
Khối `render:` — vẽ trực quan (alias `plots:`)
Tổ chức theo `panel "name":`; mỗi panel chứa lệnh `line`, `band`, `marker`, `level`, …
`candora` / `ohlc` — nến tùy chỉnh
Vẽ nến OHLC tùy chỉnh. Border tùy chọn: `in lime` (body=border) hoặc `in lime and pink` / `border: pink`. Alias: `ohlc`.
`liquid` / `vol` — tích hợp Volume dưới chart nến
Volume dưới pane nến — một lớp màu (`in lime` / `body:`) + trend MA tùy chọn. Alias: `vol`.
`line(data, color, width, dash, title)`
Vẽ đường — input là Series với DatetimeIndex.
`marker(mask, shape, color, location)`
Đánh dấu các bar mà mask=True. shape CANDORA: circle, square, arrow_up/down (mũi tên có cán), triangle_up/down (tam giác), cross, diamond. location: above_bar/below_bar/at_price.
`level(price, color, dash, label)`
Đường ngang giá cố định — phù hợp 70/30 RSI, support/resistance.
`band` — vùng fill (Bollinger / Keltner / Donchian)
Fill giữa hai series hoặc struct indicator; hỗ trợ màu động và viền solid/dash/dot.
`ribbon` — vùng tô giữa hai series
Envelope fast/slow (EMA, …); màu fill động; viền solid/dash/dot; không vẽ mid.
`zone` / `background` — tô vùng (full hoặc limit)
Alias v2 `zone`: mode **full** (tô full trục giá theo span thời gian) hoặc **limit by [lo, hi]** (hộp FVG/SMC giới hạn giá + extend bar).
`histogram` / `hist` — cột histogram
Cột — MACD hist, spread, volume. Story: `hist series as "…" in color`.
`box(from, to, color, opacity, borderStyle)`
Hộp chữ nhật giữa hai anchor `[thời gian, giá]` — supply/demand, vùng Long→swing high. Verb v2: **`box`** (canonical kind nội bộ: `rectangle`).
`text(mask, label, location, color, size)`
Nhãn chữ trên chart — mask form (nhiều điểm) hoặc `at: [t, giá]` (một điểm). Font scale theo zoom nến (giống marker label).
`trendline` — đường xu hướng (verb v2 + truyền thống)
Story: `trendline [t,p]` (chain) · `clone to [t,p]` (kênh giá) · `filled` · `limit by N`.
`fibo` — Fib retracement (verb v2)
Story: `fibo [t1,p1] to [t2,p2] as "…" in color [solid|dashed|dotted] [filled] with levels […] with opacity Npct with extend …`. Canonical kind: `fibonacci`.
`vpvr(rows, va, side, …)` — Volume Profile Visible Range
Profile khối lượng cố định theo dải giá visible range — buy/sell split, POC, value area; tự recompute khi pan/load tile.
`vpfr(from, to, rows, va, …)` — Volume Profile Fixed Range
Profile khối lượng trong span thời gian giữa hai anchor `[t, giá]` — zigzag legs, buy/sell split, POC, value area.
Khối Act (3)
Act Quanta story — enter / close / signal
Block `act:` dùng cú pháp Quanta story, hoặc hàm truyền thống
Order primitives — buy/sell/order
Paper/live: `buy`/`long`/`sell`/`short` (qty|weight|limit|tag|note|all), story `enter`/`close` (+ alias buy|sell).
`quanta score` / `signal(...)` — allocator output
Story (mặc định AI): `quanta score expr with strong|conf|confidence conf note "…"`. Legacy: `signal(score:, confidence:, rationale:)`.
Khối Risk (1)
Hàm: Trend (5)
Hàm: Momentum (7)
Hàm: Volatility (6)
Hàm: Volume (2)
Hàm: Strength (2)
Hàm: Logic (5)
Hàm: Timeseries (15)
hhv
Highest high value n bar.
llv
Lowest low value n bar.
prev
Lag n bar (≡ x[n]).
lag
Alias của prev.
diff
x − x.shift(n).
pctchange
Thay đổi theo kiểu pandas.pct_change (phân số; 0.01 = +1%). Khác roc (roc trả %).
rollmean
Mean rolling n.
rollstd
Std rolling n.
rollsum
Sum rolling n.
rollmin
Min rolling n.
rollmax
Max rolling n.
zscore
Z-score; ``window=None`` → toàn series, có window → rolling.
rankpct
Rank percentile (0..1) trong window.
barssince
Số bar kể từ khi cond=True gần nhất (NaN nếu chưa từng).
valuewhen
2 đối số: lấy x khi cond=True rồi forward-fill (kéo giá trị pivot/sự kiện sang các bar sau). 3 đối số: x khi True, default khi False. Không dùng 0 làm default cho thời gian/giá nếu sau đó đưa vào trendline/plot — engine/ChartCmd coi time=0 là không hợp lệ.
Hàm: Math (12)
abs
|x|.
ceil
Ceil.
floor
Floor.
sqrt
√x.
log
ln(x).
log1p
ln(1+x), an toàn cho returns nhỏ.
exp
e^x.
sign
−1 / 0 / +1.
tanh
tanh(x), bound (−1,1) — hữu ích score.
clip
Giới hạn [lo, hi]. Story: `limit x by lo and hi`.
safediv
Chia vector/scalar an toàn — b=0 hoặc NaN → fallback (tránh crash slope, tỷ lệ).
iif
Vectorized ternary: iif(cond, a, b). Story: `a when|if cond else b`. Khối `when`/`if` trong act/score — xem syntax/when.
Hàm: Pivot (2)
Hàm: Risk (1)
Hàm: Signal (1)
Hàm: Debug (1)
Bài mẫu (6)
Bài 1 — Chiến lược đầu tiên: EMA cross
Dạy header + params/detect/act/render (Quanta Story) qua EMA golden cross.
Bài 2 — Study đa panel: BB + RSI
Dùng `study` (chỉ vẽ, không `act`) để minh hoạ Bollinger Bands + RSI 14 theo Quanta Story.
Bài 3 — Mean reversion với guard regime
RSI<30 + chạm BB dưới → enter long; chỉ khi ATR thấp (range). Guard regime trong detect.
Bài 4 — Donchian breakout + volume confirm
Breakout kênh 20 ngày, lọc volume > 1.5× trung bình. Dạy `donchian`, `d.upper[1]`, filter.
Bài 5 — Quản lý thoát: trailing ATR stop
Dùng `get … when` (valuewhen) để neo điểm vào, trailing stop bằng ATR, `enter`/`close` Story.
Bài 6 — Pivot high + trendline trên chart (tránh lỗi valuewhen)
ffill pivot với `valuewhen(ph, …)`; hai anchor `trendline`; `safediv` slope; peak exit + mark.
Ví dụ (3)
Momentum 12-1 + MA filter
Cổ điển: ROC 252 ngày trừ tháng cuối, kết hợp MA50/MA200 trend filter.
Volatility targeting (kích thước weight tỷ lệ ngược ATR%)
score×confidence kết hợp 1/ATR% → meta-allocator phân bổ ưu tiên mã yên tĩnh.
Đánh dấu nhiều điều kiện trên chart
Chỉ nhận tín hiệu khi RSI thoát vùng oversold + volume thrust + MACD cross.
AI & pitfalls (1)
Xin chào! Tôi là trợ lý học ngôn ngữ Quanta. Hỏi tôi về cú pháp, hàm, hoặc cách viết một chiến lược cụ thể (ví dụ: "Làm sao để xác định đỉnh đáy để vẽ trendline?").