Skip to content

Latest commit

ย 

History

History
466 lines (360 loc) ยท 30.6 KB

File metadata and controls

466 lines (360 loc) ยท 30.6 KB

Copyright (C) 2024-2026 jango_blockchained

This file is part of pynescript.

pynescript is free software: you can redistribute it and/or modify

it under the terms of the GNU Affero General Public License as published by

the Free Software Foundation, either version 3 of the License, or

(at your option) any later version.

pynescript is distributed in the hope that it will be useful,

but WITHOUT ANY WARRANTY; without even the implied warranty of

MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License

along with pynescript. If not, see https://www.gnu.org/licenses/.

SPDX-License-Identifier: AGPL-3.0-or-later

Missing Features - Pine Script v6 Implementation

Current Status (as of 2026-08-19, hoox-pyne 0.3.17): Strong core support (parser + evaluator + 2474 collected tests). Open-source corpus set01โ€“04 (local measurement, not shipped in git): parse 99.96% (2476/2477), Runtime interpret 100% excl. EXPECTED_FAIL (2466 OK + 11 intentional demos), set01 249/249 โ€” not a claim of 100% TradingViewยฎ platform parity. Drawing max_*_count GC landed. Alert engine + L2 webhooks closed on Pro API and pyne-worker. Warm-compile (H2) + series caps (T1) + incremental TA (bb/kama/cmo/stochrsi/wma/hma/linreg + 0.3.10 volume obv/wad/wvad/cmf/klinger) landed. Package Runtime SoT + pyne-worker thin wrap landed (H1 largely done). Compile object-mode residuals (0.3.16โ€“0.3.17): UDF locals / free-series, nopython None/unicode, matrix handles, x = switch, UDT returns, drawing/chart.point copy, Pine int(na), sanitize chrome, round() extras, import stubs as na, color/bool/float UDF type dispatch, nested UDT method field types. Residual: interpretโ†”compile plot MISMATCH corpus tail (P1p). Incremental ta.nvi/ta.pvi and Supertrend midยฑfactorยทATR goldens landed.

Last Updated: 2026-08-19 (align with docs/ROADMAP.md + 0.3.17; pine-worker is not colocated)

Overall Support Assessment: ~99%+ for core v6. Multiline strings + export const integrated. Remaining gaps are mostly by-design (mock/foreign request data, platform/editor-only) plus long-tail Runtime fails on truncated scrape sources โ€” not missing alert/webhook/drawing-GC product surface.

  • Parser: Excellent for v5/v6 core + multiline, soft keywords, bitwise, typed UDF returns.
  • Evaluator/Builtins: Broad coverage + data context injection + incremental hot-path TA + alert freq engine.
  • Recent: corpus sanitize, series caps, warm-compile, dual-host alerts + L2 webhooks, drawing GC, plot parity harness.
  • Full test runs + lint clean targeted. See details.

Latest Pine Script Releases & Gaps (2024-2026)

Pine Script v6 launched December 2024, followed by monthly updates. Key sources: official release notes and migration guide.

v6 Launch Features (Dec 2024) - Mostly Supported

  • โœ… Dynamic requests (series strings for symbol/tf by default, inside loops/conditionals/scopes) โ€” partial-to-good support in request.py + extensive tests.
  • โœ… Strict bool (never na); short-circuit and/or โ€” implemented in expressions.py.
  • โœ… text_size as int (points) + text_formatting (bold/italic) โ€” partial (noted in plotting.py, drawing).
  • โœ… Enums, polylines, runtime logging (log.*), negative array indices, truediv (5/2=2.5), strategy improvements โ€” supported or stubbed.
  • โœ… Full dynamic request.*() for every function + all contexts โ€” expanded with shared _resolve_symbol + _get_request_data helpers. security/lower_tf + dividends/earnings/splits/financial/quandl/economic/currency/footprint now support dynamic symbols (list/series last), data_feed scaling where applicable.

2025-2026 Monthly Updates - Significant Gaps

  • Footprint requests (Jan 2026): request.footprint(), footprint type, volume_row type + methods (buy_volume(), vah(), etc.).
    • Status: โœ… Mock data generator + methods + now dynamic symbol + data_feed volume scaling in _handle_request_footprint.
  • active parameter on input.*() (July 2025): active to enable/disable inputs in settings.
    • Status: โœ… Integrated โ€” accepted across all input handlers, stored in metadata dict (default true). Metadata-driven for backends/LSP.
  • Multiline strings ("""...""" / '''...''', April 2026): Literal strings spanning lines (auto newlines, literal indentation).
    • Status: โœ… Fully wired (2026-07-20). Generated lexer includes TRIPLE_* rules; LexerBase skips wrap-indent stripping for triple quotes; unparser prefers """...""" when value has newlines.
  • Library export const (June 2025): Export const int/float/bool/color/string from libraries.
    • Status: โœ… Implemented (2026-07-20). Parser EXPORT? on name initialization; Assign.export in ASDL; builder + unparser.
  • Sorting UDT collections with sort_field (April 2026): array.sort(), array.sort_indices(), matrix.sort() accept sort_field (const int index or string name) for UDT arrays/matrices.
    • Status: โœ… Implemented (arrays pre-existing; matrix added with UDT key support + basic numeric sort).
  • Binary search in UDT arrays (August 2026): array.binary_search(), array.binary_search_leftmost(), array.binary_search_rightmost() accept sort_field (const int index, default 0, or const string name).
    • Status: โœ… Implemented (interpret + compile object-mode; same field-key rules as UDT sort).
  • once conditional structure (August 2026): fire a block the first time the optional condition is true on a closed bar; no return value.
    • Status: โœ… Implemented in 0.4.4 (grammar + ASDL Once, interpret confirmed-bar latch, compile historical flags, LSP keyword, VS Code TextMate). Soft keyword so once as an identifier still parses.
  • Other updates (multiline in editor, line wrapping changes, dynamic loops, bid/ask on 1T, etc.): Mostly editor or minor; runtime support varies (bid/ask referenced in tests).

Current Missing / Incomplete Features List (Accurate as of July 2026)

High Priority (Syntax / Core Language - Breaks 100% Parser)

  • โœ… Multiline string literals (""" / ''' delimiters) โ€” resource lexer rules + committed generated lexer; LexerBase preserves triple-quoted newlines/indent (does not strip wrap-indent); unparser emits triple quotes for multiline values; real tests assert content + roundtrip.
  • โœ… Library export const (June 2025) โ€” parse/AST/unparse + runtime: library scripts register exports; import user/Lib/1 as x resolves via in-process registry / register_library_source; x.MEMBER attribute access; exported functions callable; exported types (export type + .new) and enums (export enum + members) via import alias.
  • โœ… UDT collection sorting with sort_field โ€” arrays had support; matrix.sort + matrix.sort_indices now fully implemented in Matrix class + evaluator mixin with int index or str name + UDT get_field keys.
  • โœ… Binary search in UDT arrays (August 2026) โ€” array.binary_search* honor sort_field (int index default 0, or string name) on UDT collections, matching sort.
  • โœ… once conditional structure (August 2026, 0.4.4) โ€” statement-only; interpret commits on barstate.isconfirmed; compile is historical.
  • โœ… Additional v6 syminfo/timeframe constants (isin, current_contract, main_tickerid, main_period) added to default context.
  • โœ… behind_chart on indicator/strategy/library, force_overlay on drawing objects (line, box, label, polyline, table) and plot() - captured in metadata and ctors.
  • โœ… timeframe_bars_back documented and accepted in time()/time_close().

Medium Priority (Builtins / Recent Additions)

  • โœ… Full request.footprint() + footprint/volume_row types and methods. Mock data generator + all listed methods (buy/sell/delta/vah etc) implemented in request.py. (Real data by design not present.)
  • โœ… active parameter on all input.*() functions โ€” accepted in all handlers (generic + specific bool/int/float/.../enum/color), stored in returned metadata dict with default True. Runtime/UI effect is metadata-driven (for backends/LSP); integrated July 2025+ followups.
  • โœ… Complete text_formatting + integer text_size โ€” text_size now supports int (points) or size.* consts in Label (and context has size.auto/tiny/...). text_formatting wired for labels. Extended to plot(). Real size values supported.
  • โœ… Dynamic requests full coverage: all major request.* now use dynamic resolution; works inside loops/conditionals (args visited by evaluator). Datafeed provides live values.
  • โœ… Dynamic for loop end bounds (v6): now re-evaluated each iteration in visit_ForTo.
  • โœ… Enums full runtime + type integration โ€” visit_EnumDef, member .attr access, symbolic + value support, context storage, works in expr/switch/assign. Added BuiltinTypeKind.ENUM + registry entry. input.enum supported (metadata + defaults). LSP semantic tokens + metadata; completion/hover for user enums partial.
  • โœ… strategy.exit() v6 pair evaluation (limit/profit + stop/loss) โ€” chooses based on current price which activates first.
  • โœ… ticker renko/pointfigure/kagi support "PercentageLTP" style (v6).
  • โœ… Realtime data feeds (CCXT Pro + Mock/Composite) โ€” full module, sync wrappers, broker for orders/positions, wired to request.security + lower_tf + evaluator context + backend. (July 2026)
  • โœ… Strict boolean semantics โ€” core short-circuit, na->false in conditions implemented in expressions/statements. Edge cases covered in v6 tests; no na bools in main paths.

Lower Priority / Platform Features

  • Real (non-mock) data for request.*() (by design for this library).
  • request.security foreign data on compile โ€” still not filled. Compile lowers only chart-symbol simple OHLCV; foreign tickers and complex security expressions emit na (no invent of chart series as foreign fundamentals / advance-decline volume). Interpret path may still serve mocks or wired feeds. Parity tests expect all-na foreign UDF plots on both hosts when data is absent (tests/test_dividend_yield_parity.py).
  • Auto Fib Extension/Retracement (and similar pivot scripts) โ€” need real pivot/swing structure (or a registered TradingView/ZigZag library). Flat synthetic bars intentionally surface the same insufficient-pivot runtime.error on interpret and compile (both_error_same in scripts/compare_interp_compile.py); do not โ€œfixโ€ by inventing pivots.
  • โœ… Real effects for plots โ€” Plot dataclass + PlotRegistry; plot(), plotshape, plotarrow now register instances. Other plot* lightweight. Extended ticker styles with PercentageLTP support for renko/kagi/pointfigure.
  • Some strategy backtest trimming / unlimited history behaviors (high-level support exists).
  • โœ… Strategy runtime depth (2026-07-20): open trades list, signed strategy.position_size, opentrades/closedtrades counts, netprofit/openprofit/equity/grossprofit/grossloss/wintrades/losstrades, mark-to-market vs close, partial closes; golden multi-bar tests in tests/test_strategy_runtime.py.
  • โœ… Strategy extended series (2026-07-20): avg_trade/avg_winning_trade/avg_losing_trade + percent forms, *_percent for net/open/gross, cash, account_currency, position_entry_name, opentrades.capital_held, closedtrades.first_index, eventrades, max_drawdown/max_runup (+ percent), max_contracts_held_*, margin_liquidation_price (na).
  • โœ… Drawing *.all collections (2026-07-20): line/box/label/table/polyline.all return non-deleted DrawingRegistry objects; linefill.all empty until modeled.
  • โœ… last_bar_index / last_bar_time resolve as series (context override or bar_index/time fallback).
  • โœ… strategy.risk.max_position_size(percent) caps entry qty by equity %.
  • โœ… Plotting real effects (2026-07-20): all plot*/hline/bgcolor/barcolor/fill register on PlotRegistry; plot() returns Plot id for fill.
  • โœ… request.* data_feed depth: shared _ohlcv_closes/_ticker_last; MockDataFeed sync fetch_latest_*; currency_rate prefers feed pair; seed stored in context.
  • โœ… Numba compile path (MVP, 2026-07-20): pynescript.compiler.compile_script / Runtime.run(mode="compile") โ€” Pine โ†’ @numba.njit bar loop for ta.sma/ema/rsi, plots, history, inputs. See docs/COMPILER_PLAN.md.
  • โœ… Compile object mode (2026-07-20): UDTs, maps, full drawing surface auto-switch to Python/numpy bar loop; __drawings events + plots.
  • โœ… Compile object-mode corpus residuals (0.3.16โ€“0.3.17): UDF if/for-in locals, nested UDF free-series (a_arr / vol_arr), nopython None/timezone timestamp, object valuewhen/running_max, matrix UDF/kron handles, statement x = switch, UDT Type.new() returns, chart.point.copy/box.copy, pine_int(na), sanitize of Hugo//* *//jinja chrome, round() extras, import stubs as na, color type dispatch, nested UDT methods. Leftover: INV expected-fail fixtures, P1p plot MISMATCH tail.
  • Editor-specific (word wrap defaults, etc.) โ€” irrelevant for this runtime/parser.
  • Minor post-2025 behaviors (specific request.* changes, updated wrapping rules if they affect AST).

Already Well Supported (from v6+)

  • Dynamic requests (core), short-circuit bool logic, negative array indices, truediv, polylines, logging, bid/ask refs, var/varip, most TA/strategy builtins, UDTs, collections, full parser for pre-2026 v6.

Matrix surface (2026-07-25)

  • โœ… Official TV matrix linear algebra: det, inv, pinv, eigenvalues, eigenvectors, kron, pow, trace, rank, mult, diff
  • โœ… Official names: matrix.avg/min/max/mode/sum/median/stdev/variance, row/col/submatrix/sort/sort_indices/reverse/swap_*
  • โœ… Predicate suite: is_square/zero/identity/diagonal/antidiagonal/symmetric/antisymmetric/triangular/binary/stochastic
  • โœ… runtime.error, input.text_area, ta.percentile_linear_interpolation, ta.percentile_nearest_rank
  • โœ… input.* now returns values (Pine semantics) with metadata side-channel _input_declarations

Full reference surface (2026-07-25 cont.)

  • โœ… 0 missing vs official TV v6 function reference list (434 symbols checked against live dispatch)
  • โœ… TA: ta.alma, ta.bbw, ta.cmo, ta.correlation
  • โœ… Drawing: full linefill.*, line.get_price/set_xy*/set_*_point, box text setters, label set_point/set_size/set_textalign, table cell/frame setters
  • โœ… strategy.risk.max_drawdown / max_cons_loss_days / allow_entry_in
  • โœ… max_bars_back, ticker.inherit
  • โœ… Footprint/volume_row accessors (rows, total_volume, get_row_by_price, imbalances)
  • โœ… Runtime plot values are bar scalars (not nested full-series lists)
  • โœ… Bar-mode TA (_pine_bar_mode): ta.sma/ema/rma/vwma/atr/tr return current scalar in Runtime, full series in unit/list mode
  • โœ… strategy.risk.allow_entry_in / max_drawdown / max_cons_loss_days enforced at strategy.entry (blocked entries emit order + risk_blocked)
  • โœ… Inventory summary regenerated from live dispatch (640 callables)
  • โœ… Broker: process_pending_orders fills limit/stop/stop-limit (and market next bar); partial fills via max_fill_per_bar; stop/limit strategy.entry pending; na prices coerced
  • โœ… ta.kama/dema/tema bar-mode scalars; request.seed seeds stdlib + numpy for reproducible mocks
  • โœ… OCA: strategy.oca.none/cancel/reduce + oca_name/type on orders; fill cancels/reduces siblings
  • โœ… Commission (percent / cash_per_order / cash_per_contract) + slippage ticks from strategy() kwargs; applied on fills
  • โœ… Compile-mode strategy (object mode): CompileStrategyBroker emits entry/close/order/cancel events; Runtime.run(..., mode="compile") returns events; position_size/equity/netprofit available
  • โœ… Compile pending fills: limit/stop/stop-limit/market pending orders + OCA reduce/cancel; process_pending_orders each bar before script body (interpreter-aligned)
  • โœ… Datafeed wiring: ChartOHLCVProvider from Runtime bars; resolve_request_sources(); Composite sync fetch_latest_*; /run accepts data_source/data_options/symbol

Corpus + Runtime performance (2026-07-28)

Open-source Pine corpus (tests/data/set01โ€“set04) and bar-loop throughput work. Plan: .opencode/plans/2026-07-28-runtime-performance.md, skill .grok/skills/pynescript-perf/.

Parser / sanitize (closed)

  • โœ… Soft keywords, bitwise ops, = reassignment, typed UDF returns (int f(n) => โ€ฆ)
  • โœ… corpus_sanitize for scrape chrome (fences, FMZ footers, missing commas between var decls)
  • โœ… Parse rate set01โ€“04 99.96% (2476/2477); residual 1 intentional invalid line-wrap docs demo (not a grammar hole). Truncated scrapes recovered via sanitize where high-confidence

Runtime host hygiene (closed โ€” no semantic change)

  • โœ… _pine_defs_locked after first bar (pynescript backend + pyne-worker) โ€” stops O(barsยฒ) FunctionDef/method multi-dispatch growth
  • โœ… Append-only current_series OHLCV lists (no per-bar list(reversed(history)) rebuild)
  • โœ… One-pass derived prices (hl2/hlc3/โ€ฆ) per bar on worker host
  • โœ… Worker aligns with backend: _pine_bar_mode + _pine_ta_incremental (default on)

Incremental bar-mode TA (closed โ€” golden โ‰ก full recompute)

Call-site state (_ta_call_i reset each bar), one sample per site per bar (safe with _SERIES_MAX):

Builtin Notes
โœ… ta.sma / ta.ema / ta.rma / ta.rsi O(period) / O(1) vs full-history recompute
โœ… ta.macd Fast/slow/signal internal EMAs, one slot
โœ… ta.atr Matches current full path (EMA of TR after warm-up mean)
  • Golden: tests/test_ta_incremental.py (inc โ‰ก full last values; Runtime on vs PYNE_TA_INCREMENTAL=0)
  • Disable: env PYNE_TA_INCREMENTAL=0
  • Bench (โ‰ˆ3264 BTC daily bars, worker Runtime): ~9.5ร— ta_sma, ~4.9ร— sma+ema+rsi, ~3ร— macd, ~10ร— atr, ~8.5ร— macd+atr+rsi+sma combo vs flag off

Still open / residual (not โ€œmissing syntaxโ€)

ID Item Pri
H1 Dual-host Runtime unify P1 โœ… package SoT pynescript.runtime + backend shims + pyne-worker thin wrap (sibling repo, not colocated) โ€” residual CF deploy smoke only
H2 Product warm-compile path (SLOs, prewarm, IR cache on in deploy) P1 โœ… (2026-08)
C1 Corpus Runtime residual P1 โœ… (2026-08-09) โ€” set01โ€“04 Runtime interpret 100% excl. EXPECTED_FAIL (2466 OK + 11 intentional demos); parse 99.96%. Residual = intentional demos only. set05 long-tail separate
T1 Cap unbounded current_series lists to max_bars_back / _SERIES_MAX P2 โœ… R7 โ€” PYNE_SERIES_CAP (default ON), PYNE_SERIES_MAX, goldens tests/test_series_cap.py
T2 Incremental for remaining heavy kernels P2 โœ… R7: bb/kama/cmo/stochrsi + wma/hma/linreg; 0.3.10 obv/wad/wvad/cmf/klinger + nvi/pvi; aroon/dpo/donchian/kst
L2 Webhook alerts productization P3 โœ… pyne-worker + Pro API /run export + outbound ALERT_WEBHOOK_URL / webhook_url
F1 ta.atr is Wilder RMA of TR (interpret + Numba). Supertrend is simplified midยฑfactorยทATR (not TV ratchet); goldens lock that contract P2 โœ…
โ€” Bit-identical recursive smoothers vs live TV numerical-parity track
โ€” Drawing max_*_count GC / alert engine โœ… shipped (not missing)

Canonical priority table: docs/ROADMAP.md.

Corpus Runtime snapshot (set01โ€“set04, 50 bars ยท 2026-08-09)

Stage Parse Runtime interpret
Historical baseline (pyne-worker) โ€” 1851 / 2477 (74.7%)
After early fail re-runs โ€” ~2224 / 2477 (89.8%) projected
After C1 8-agent pass (2026-08-01) ~94.8% era ~2337 / 2477 (94.3%) projected
Current (pynescript Runtime, 2026-08-09) 2476 / 2477 (99.96%) 2466 OK + 11 EXPECTED_FAIL โ†’ 100% excl. intentional demos
  • set01 Runtime: 249 / 249 (100%)
  • EXPECTED_FAIL (11): intentional library runtime.error demos, lower-TF security guards, invalid line-wrap docs demo, truncated mid-call scrape, pathological nested-loop demo
  • Not shipped in-repo (legal / ToS hygiene); measured locally from pre-drop restore
  • Not a claim of TradingViewยฎ platform or bit-identical execution parity

Recommendations

  • Prefer golden tests vs current oracle before changing TA seed rules (ATRโ†’RMA, VWMA volume, etc.).
  • Land evaluator/TA math in src/pynescript/ast/evaluator/; keep pyne-worker as thin host (timeout/R2/CF).
  • Re-run corpus fails only via scripts/corpus_rerun_fails.py / pyne-worker scripts/corpus_rerun_fails.py after each fix.
  • Update pinescript_implementation_status.md and this file after each addition.
  • Current overall: Excellent for most real-world scripts (parser + common builtins + bar Runtime). Not drop-in 100% for latest 2026 platform/editor-only or exotic broker edges.

See also:

  • docs/pine_v6_full_surface_inventory.md โ€” full schema + every inventory name (dispatch, series, language, graphs)
  • docs/pinescript_implementation_status.md (detailed โœ… matrix)
  • tests/test_v6_features.py (good coverage of dynamic requests, footprint, etc.)
  • Official: https://www.tradingview.com/pine-script-docs/release-notes/ and migration guide to v6.

๐ŸŽ‰ Project Completion Status

PyneScript core is mature, with significant July 2026 enhancements:

  • โœ… Strategy Events - Full StrategyEvent capture, parity corpus (13+ tests), strategy.long/short constants, var/varip + ReAssign support.
  • โœ… pine-worker โ€” legacy TypeScript Cloudflare Worker in sibling hoox-sh/pine-worker (not colocated). New TS library work is @hoox-sh/pynets (pynets/ submodule here).
  • โœ… 200+ Built-in Functions (including advanced strategy)
  • โœ… 1000+ Tests (core + parity + strategy events green)
  • โœ… Complete Parser - Full support for Pine Script v5-v6 grammar
  • โœ… Full AST Support - Complete abstract syntax tree representation
  • โœ… Expression Evaluator - Evaluate deterministic expressions and functions
  • โœ… Type System - All Pine Script types implemented
  • โœ… Collections - Arrays, matrices, and maps fully supported
  • โœ… Drawing Objects - All plot and drawing functions available
  • โœ… Strategy Functions - Strategy execution framework implemented

๐Ÿš€ What's Implemented

Parser & Language Features

  • โœ… Full Pine Script v5-v6 grammar support
  • โœ… ANTLR4-based parsing with robust error handling
  • โœ… Complete type system (int, float, bool, string, color, series, array, matrix, map)
  • โœ… User-defined types (UDT) and objects
  • โœ… Control flow (if/else, for, while)
  • โœ… Functions and methods
  • โœ… Comments and annotations
  • โœ… String interpolation and formatting

Built-in Functions (149+)

Technical Analysis (85+ functions)

  • โœ… Moving averages: SMA, EMA, WMA, VWMA, HMA, DEMA, TEMA, SWMA
  • โœ… Oscillators: RSI, MACD, Stochastic, Williams %R, CCI, CMO
  • โœ… Trend: ADX, Keltner Channels, Bollinger Bands, Supertrend
  • โœ… Volume: OBV, MFI, Volume Rate of Change
  • โœ… Momentum: ROC, KDJ, Ichimoku, Zigzag, Linear Regression
  • โœ… Correlation: RCI, Rank Correlation Index
  • โœ… Pattern Detection: Pivots, Support/Resistance

Math Functions (20+ functions)

  • โœ… Basic: abs, max, min, pow, sqrt, log
  • โœ… Rounding: round, floor, ceil, round_to_mintick
  • โœ… Trigonometry: sin, cos, tan, asin, acos, atan
  • โœ… Statistical: sum, avg, stddev, variance

String Functions (15+ functions)

  • โœ… Case conversion: upper, lower
  • โœ… Search: contains, startswith, endswith, substring
  • โœ… Formatting: tostring, tonumber, format
  • โœ… Length and manipulation

Array Functions (25+ functions)

  • โœ… Basic: size, get, push, pop, slice, join
  • โœ… Searching: includes, indexof, lastindexof, findindex
  • โœ… Statistics: sum, avg, min, max, stddev, variance
  • โœ… Percentiles: percentile_linear_interpolation, percentile_nearest_rank
  • โœ… Binary search: binary_search_leftmost, binary_search_rightmost
  • โœ… Sorting: sort, reverse, sort_indices

Time Functions (10+ functions)

  • โœ… Time extraction: year, month, dayofmonth, dayofweek, hour, minute, second
  • โœ… Timestamps: time, timestamp, time_close, weekofyear
  • โœ… Utilities: timenow, time_tradingday

Drawing Functions (10+ functions)

  • โœ… Plotting: plot, plotarrow, plotbar, plotcandle, plotchar, plotshape
  • โœ… Overlays: fill, hline, bgcolor, barcolor
  • โœ… All with styling options

Strategy Functions (15+ functions)

  • โœ… Orders: entry, exit, close, closeallornoorder
  • โœ… Position management: position management hooks
  • โœ… Risk management: stop loss, take profit
  • โœ… Accounting: entry price, position size

Input Functions (10+ functions)

  • โœ… All input types: int, float, bool, string, symbol, session, source, time, timeframe, color, price
  • โœ… Input validation and constraints
  • โœ… Group organization

Request Functions

  • โœ… Security data requests
  • โœ… Economic indicators
  • โœ… Splits and dividends data
  • โœ… Mock implementations for testing

Utility Functions (10+ functions)

  • โœ… Type checking: na, nz, fixnan
  • โœ… Type conversion: int, float, bool, string
  • โœ… Color operations: color.new, color.rgb
  • โœ… Alerts: alert, alertcondition (+ freq rules, host export, pyne-worker last-bar + webhooks)

Collections

  • โœ… Arrays with full manipulation support
  • โœ… Matrices with linear algebra operations
  • โœ… Maps with key-value storage
  • โœ… Statistical operations on all collections

Advanced Features

  • โœ… Series history access (close[0], close[1], etc.)
  • โœ… Expression evaluation engine
  • โœ… AST transformation framework
  • โœ… Complete round-trip parsing (parse โ†’ transform โ†’ unparse)
  • โœ… Type inference and checking

๐Ÿ“Š Implementation Metrics

Metric Value
Built-in Functions Implemented 149+
Total Test Coverage 997 tests
Test Pass Rate 100%
Grammar Completeness ~95%
Parser Success Rate ~99%
Lines of Code 15,000+
Documentation Coverage 100+ pages

๐Ÿ”„ Known Limitations

Intentional Design Decisions

  1. Mock / host data - request.* uses mock or host-injected feeds; foreign symbols on compile emit na (no invented multi-asset series)
  2. Not a TV chart host - Plot/drawing/fill are registry + export for AXIS/clients; pixels are external
  3. Deterministic bar evaluation - Interpreter + optional Numba compile (mode=auto / warm-compile); not a licensed broker
  4. Realtime optional - CCXT Pro / composite feeds exist; live multi-symbol TV-grade data remains host responsibility

Practical Constraints

  1. Performance - Interpret is Python-first; compile + incremental TA + series caps harden bar loops (not HFT microsecond infra)
  2. Numerical Precision - IEEE 754 float-based; interpretโ†”compile plot parity harness tracks residuals (not bit-identical every smoother vs live TV)
  3. Memory - Series capped via PYNE_SERIES_CAP / max_bars_back; large matrices/arrays still proportional
  4. Unicode - Limited support for non-ASCII characters in some edge cases

๐ŸŽฏ Future Enhancement Opportunities

High Value (Nice to Have)

  1. Real Data Integration

    • Live market data feeds
    • Actual economic indicators
    • Real stock split/dividend data
  2. Performance Optimizations

    • JIT compilation for critical paths
    • Vectorized array operations
    • Caching for repeated calculations
  3. Extended Analysis

    • Machine learning indicator wrappers
    • Advanced statistical functions
    • Complex derivation functions

Medium Value (Polish)

  1. Developer Experience

    • IDE integration and autocomplete
    • Debugging tools and profiling
    • Better error messages
  2. Documentation

    • Video tutorials
    • Interactive examples
    • Real-world trading examples
  3. Integration

    • Jupyter notebook support
    • API server for remote execution
    • โœ… Webhook support for alerts (pyne-worker + Pro API L2; ALERT_WEBHOOK_URL / webhook_url)

Low Value (Research)

  1. Experimental Features

    • Parallel execution
    • Distributed computing
    • Graph-based optimization
  2. Research Tools

    • Formal verification
    • Symbolic execution
    • Constraint solving

๐Ÿ“ Recommendations

For Users

  • โœ… Use pynescript for Pine Script analysis and transformation
  • โœ… Leverage 149+ built-in functions for calculations
  • โœ… Parse and unparse scripts for validation and normalization
  • โœ… Transform ASTs for custom script modifications
  • โœ… Evaluate expressions for deterministic computations

For Contributors

  • Contribute real data adapters for request functions
  • Optimize hot paths for performance-critical use cases
  • Extend evaluator for additional deterministic functions
  • Add domain-specific analysis tools
  • Improve error messages and diagnostics

For Production Deployment

  • โœ… Suitable for offline script analysis
  • โœ… Good for batch processing and validation
  • โœ… Excellent for educational purposes
  • โš ๏ธ Limited for real-time trading (mock data only)
  • โš ๏ธ Requires additional components for live integration

๐Ÿ“š Related Documents


July 2026 Additions (Main Consolidation)

  • Full strategy event system: StrategyEvent dataclass, event emission from all strategy.* calls, bar_index/time threading, parity fixtures for testing against TS port.
  • pine-worker is not in this tree (removed 0.3.7). Sister hoox-sh/pine-worker holds the legacy TS Worker + historical scripts/convert-python-to-ts.py. PyneTS (pynets/ submodule / standalone hoox-sh/pynets) is the TS library.
  • var / varip declaration modes and ReAssign handling.
  • Updated test coverage with dedicated test_strategy_events.py and test_parity.py.

Conclusion: Core Pine Script language/builtins are mature. Julyโ€“August 2026 work added strategy events, package Runtime SoT, corpus hardening, incremental TA (through 0.3.10 volume kernels), and dual-host hosts. The TypeScript Worker is a sister repo, not an in-tree extra. Remaining work is plot-parity residual, leftover full-list TA (nvi/pvi), optional fidelity goldens, and real data adapters โ€” not missing syntax.


Last updated: 2026-08-17
Version: 1.3 (0.3.12)