### Example folder layout Source: https://github.com/be-thomas/openpinescript/blob/main/CONTRIBUTING.md Illustrates the required top-level folder structure with version folders and common. Below the first level, organization is flexible. ```text runtime/v1/… transpiler/common/index.ts grammar/v5/PineV5Parser.g4 tests/v4/… scripts/common/… conformance/v3/golden/… ``` -------------------------------- ### Verify and write documentation examples with fetch-doc-examples.mjs Source: https://github.com/be-thomas/openpinescript/blob/main/examples/common/tradingview-docs/README.md Commands to verify that downloaded documentation examples match their source digests, or to re-download and rewrite them. The verify command fails on any drift. ```bash node scripts/common/fetch-doc-examples.mjs verify # fails on any drift node scripts/common/fetch-doc-examples.mjs write # re-download and rewrite ``` -------------------------------- ### Summary JSON output format Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Example of the JSON file written by --out-summary, containing strategy performance metrics. ```json { "net_profit": 4821.00, "net_profit_percent": 4.82, "gross_profit": 7200.00, "gross_loss": 2379.00, "total_closed_trades": 38, "winning_trades": 24, "losing_trades": 14, "win_rate": 63.16, "avg_win": 300.00, "avg_loss": 169.93, "profit_factor": 3.028, "max_drawdown_percent": 3.17 } ``` -------------------------------- ### Verify doc examples with fetch-doc-examples.mjs Source: https://github.com/be-thomas/openpinescript/blob/main/docs/common/CONFORMANCE.md Re-downloads every TradingView documentation page and compares SHA-256 digests against MANIFEST.json to confirm byte-identity of the 763 Pine Script examples. ```bash node scripts/common/fetch-doc-examples.mjs verify ``` -------------------------------- ### Start interactive REPL Source: https://github.com/be-thomas/openpinescript/blob/main/README.md Launches the interactive REPL for exploring Pine Script expressions. ```bash npm run replv2 ``` -------------------------------- ### Clone and install OpenPineScript Source: https://github.com/be-thomas/openpinescript/blob/main/README.md Clones the repository, changes into the project directory, and installs dependencies with npm. ```bash git clone https://github.com/be-thomas/OpenPineScript.git cd OpenPineScript npm install ``` -------------------------------- ### Catching a regression mid-comparison Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Run a backtest with comparison and output the comparison report to a custom directory. The example shows a PARTIAL result with a trade discrepancy, useful for catching regressions. The output includes a FAIL on trades and a PASS on chart and summary. ```bash npm run opsv2 -- strategy.pine --data data.csv \ --compare-dir ./tv_exports \ --out-comparison ./reports ``` ```diff Compiling: strategy.pine... Running backtest: 506 bars... + ✔ Done. === Comparison Report === Overall: PARTIAL Tolerance: 0.0001 + Chart Data: PASS (506 rows, 0 mismatches) - Trades: FAIL (38 tv / 37 opsv2 — 1 discrepancy) - Trade #37: missing_in_opsv2 + Summary: PASS (net profit Δ 0.0000%) + Report written: ./reports/comparison_report.json ``` -------------------------------- ### Summary PASS output Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Output when all fields match. Shows net profit delta percentage. ```diff + Summary: PASS + Net profit Δ% : 0.0000 ``` -------------------------------- ### Trades CSV output format Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Example of the CSV written by --out-trades. TradingView-compatible, one entry + one exit row per trade. ```text Trade #,Type,Signal,Date/Time,Price,Contracts,Profit,Profit %,Cum. Profit 1,Entry Long,Buy_Sig,2024-03-01T10:00:00.000Z,45000.0000,1,0.00,0.00,0.00 1,Exit Long,Take_Profit,2024-03-01T14:00:00.000Z,46000.0000,1,1000.00,2.22,1000.00 2,Entry Long,Buy_Sig,2024-03-02T09:30:00.000Z,46100.0000,1,0.00,0.00,1000.00 2,Exit Long,Stop_Loss,2024-03-02T15:00:00.000Z,45800.0000,1,-300.00,-0.65,700.00 ``` -------------------------------- ### Run the REPL with npm Source: https://github.com/be-thomas/openpinescript/blob/main/repl/common/README.md Starts the Pine Script read-eval-print loop. Use the -v flag for verbose lexer and parser output. ```bash npm run repl npm run repl -- -v # verbose: lexer + parser output ``` -------------------------------- ### Chart CSV output format Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Example of the CSV written by --out-chart. Cells are empty (not NaN) during the indicator warm-up period. ```text time,open,high,low,close,volume,SMA_20,RSI_14 2024-03-01T00:00:00.000Z,150.5,151.2,149.8,151.0,12000,148.5,65.2 2024-03-04T00:00:00.000Z,151.0,152.0,150.5,151.8,15000,148.8,68.1 ``` -------------------------------- ### Output summary: --out-summary Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Writes the strategy performance summary as a JSON file. The command and its success output are shown together. ```bash npm run opsv2 -- strategy.pine --data data.csv --out-summary ./results/summary.json ``` ```diff Compiling: strategy.pine... Running backtest: 506 bars... + ✔ Done. + ✔ Summary → ./results/summary.json ``` -------------------------------- ### Report written output Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Confirmation message when the comparison report is written. ```diff + Report written: ./reports/comparison_report.json ``` -------------------------------- ### Run opsv2 with --compare-summary Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Compares the performance summary from opsv2 against a TradingView summary export. Accepts both JSON and key-value CSV formats. ```bash npm run opsv2 -- strategy.pine --data data.csv --compare-summary ./tv_exports/summary.json ``` -------------------------------- ### Verify generated parsers are byte-identical Source: https://github.com/be-thomas/openpinescript/blob/main/CONTRIBUTING.md Command to compute a hash of all generated parser files to verify that the build produces byte-identical output. Run this after changing the build. ```bash find parser -path '*/generated/*' -type f | sort | xargs shasum | shasum ``` -------------------------------- ### Full export + comparison in one command Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Run a backtest with full export and comparison in a single command. Exports chart, trades, and summary to the specified output directory, compares against TradingView exports with a tolerance of 0.001, and writes a comparison report. The output shows the generated files and a PASS result. ```bash npm run opsv2 -- strategy.pine --data data.csv \ --out-dir ./results \ --compare-dir ./tv_exports \ --tolerance 0.001 ``` ```diff Compiling: strategy.pine... Running backtest: 506 bars... + ✔ Done. + ✔ Chart → ./results/chart.csv + ✔ Trades → ./results/trades.csv (38 trades) + ✔ Summary → ./results/summary.json === Comparison Report === Overall: PASS Tolerance: 0.001 + Chart Data: PASS (506 rows, 0 mismatches, max Δ 2.9e-5) + Trades: PASS (38 tv / 38 opsv2) + Summary: PASS (net profit Δ 0.0000%) + Report written: ./results/comparison_report.json ``` ```text results/ ├── chart.csv ├── trades.csv ├── summary.json └── comparison_report.json ``` -------------------------------- ### Basic invocation: npm run opsv2 -- --data [flags] Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Shows the required command structure. script.pine and --data are always required; all other flags are optional. Without output or comparison flags, a formatted summary is printed to the terminal and nothing is written to disk. ```bash npm run opsv2 -- --data [flags] ``` -------------------------------- ### Tolerance effect comparison Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Shows how tightening or loosening the tolerance changes which rows fail. ```diff # With --tolerance 0.0001 (default) - Chart Data: FAIL (3 mismatched rows, max Δ 5.23e-2) # With --tolerance 0.1 + Chart Data: PASS (506 rows compared, max Δ 5.23e-2 — within tolerance) ``` -------------------------------- ### Redirect stderr for clean JSON output Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md With no output or comparison flags, stdout carries a strict JSON document and stderr carries the human-readable summary. Redirect stderr to get clean, pipeable JSON. ```bash npm run opsv2 -- strategy.pine --data data.csv 2>/dev/null ``` ```json { "script": "strategy.pine", "bars_processed": 506, "inputs": [ { "id": "input_0", "title": "Fast Length", "type": "integer", "default": 9, "current": 9, "overridden": false }, { "id": "input_1", "title": "Slow Length", "type": "integer", "default": 21, "current": 21, "overridden": false } ], "performance": null } ``` -------------------------------- ### Summary FAIL output Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Output when a field diverges. Lists field mismatches with values and deltas. ```diff - Summary: FAIL - Net profit Δ% : 0.0652 - Field mismatches: - net_profit_percent opsv2=4.82 tv=4.88 Δ=6.00e-2 - win_rate opsv2=63.16 tv=64.00 Δ=8.40e-1 ``` -------------------------------- ### Run script once to discover input IDs Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Run the script without overrides to list available input IDs. The output shows a summary with input IDs like input_0 and input_1, and a tip to override with --input. ```bash npm run opsv2 -- strategy.pine --data data.csv ``` ```diff === strategy.pine — Summary === ... Script Inputs: input_0 "Fast Length" [integer] = 9 (default) input_1 "Slow Length" [integer] = 21 (default) Tip: override with --input input_0= ``` -------------------------------- ### Trades PASS output Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Output when all trades match. Shows trade counts from both sources. ```diff + Trades: PASS TV trades : 38 opsv2 trades : 38 ``` -------------------------------- ### Run with --dry-run to discover inputs Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Executes a single bar and emits the same JSON, then exits. Use it to discover a script's input() variables without paying for a full backtest. ```bash npm run opsv2 -- strategy.pine --data data.csv --dry-run 2>/dev/null ``` -------------------------------- ### Complete example: transpile, run in VM, read result Source: https://github.com/be-thomas/openpinescript/blob/main/transpiler/common/transpiler-usage.md Transpiles a Pine script with a function definition, runs it in a Node vm sandbox, and reads the result. The emitted JavaScript uses let and function declarations; replace let with var to expose bindings on the sandbox. ```TypeScript import { transpile } from "./transpiler/v2"; const pine = ` double(x) => x * 2 y = double(7) `; const js = transpile(pine); console.log(js); // let opsv2_y = opsv2_double(7); // function opsv2_double(opsv2_x) { return opsv2_x * 2; } // (order may vary) // Run in VM and read result import * as vm from "node:vm"; let runnable = js.replace(/\blet\b/g, "var"); const sandbox: Record = Object.create(null); vm.createContext(sandbox); vm.runInContext(runnable, sandbox); console.log(sandbox.opsv2_y); // 14 ``` -------------------------------- ### Run REPL in normal or verbose mode Source: https://github.com/be-thomas/openpinescript/blob/main/repl/v2/README.md Start the REPL with npm run repl. Use the -v flag to show lexer and parser output for each input. ```bash npm run repl # normal mode npm run repl -- -v # verbose: show lexer and parser output for each input ``` -------------------------------- ### Output trades: --out-trades Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Writes the trade log as a CSV, only meaningful for strategy() scripts. The command and its success output are shown together. ```bash npm run opsv2 -- strategy.pine --data data.csv --out-trades ./results/trades.csv ``` ```diff Compiling: strategy.pine... Running backtest: 506 bars... + ✔ Done. + ✔ Trades → ./results/trades.csv (38 trades) ``` -------------------------------- ### Run opsv2 with --tolerance Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Sets the epsilon for all floating-point comparisons. Defaults to 0.0001. Any deviation <= tolerance counts as a pass. ```bash npm run opsv2 -- strategy.pine --data data.csv \ --compare-chart ./tv_exports/chart_data.csv \ --tolerance 0.1 ``` -------------------------------- ### Trades FAIL output Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Output when there is a count mismatch or price discrepancy. Lists discrepancies with details. ```diff - Trades: FAIL TV trades : 38 - opsv2 trades : 37 - Count delta: -1 - Discrepancies (first 2): - Trade #37: missing_in_opsv2 - Trade #42: exit_price_mismatch — tv=45000.5000 opsv2=45001.0000 Δ=0.5 ``` -------------------------------- ### Warning when --out-trades on indicator Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Shows the warning displayed when the script is an indicator and produces no trades. ```diff Compiling: indicator.pine... Running backtest: 506 bars... + ✔ Done. - ⚠ Warning: --out-trades requested but no trades were recorded. - Is this an indicator rather than a strategy? ``` -------------------------------- ### Run opsv2 for numerical discrepancy report Source: https://github.com/be-thomas/openpinescript/blob/main/CONTRIBUTING.md Command line for running the opsv2 tool to compare engine output against TradingView exports. Attach the exports and this command when reporting a numerical discrepancy. ```bash npm run opsv2 -- your_script.pine --data your_data.csv \ --out-dir ./results --compare-dir ./tv_exports ``` -------------------------------- ### Inject helpers into sandbox Source: https://github.com/be-thomas/openpinescript/blob/main/transpiler/common/transpiler-usage.md Provides built-in functions or callbacks under the opsv2_ prefix so Pine code can call them. The example injects opsv2_getArr and opsv2_plot, then runs transpiled code that destructures the array. ```TypeScript const sandbox: Record = { opsv2_getArr: () => [1, 2, 3], opsv2_plot: (x: number, opts?: { opsv2_width?: number }) => { /* ... */ }, }; vm.createContext(sandbox); vm.runInContext(transpile("[a,b,c] = getArr()\n").replace(/\blet\b/g, "var"), sandbox); // sandbox.opsv2_a === 1, sandbox.opsv2_b === 2, sandbox.opsv2_c === 3 ``` -------------------------------- ### Show transpiled JavaScript with --show-transpiled Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Run the transpiler with the --show-transpiled flag to print the generated JavaScript before execution. Useful for tracing unexpected behavior in complex scripts. The output shows the transpiled code and a success message. ```bash npm run opsv2 -- strategy.pine --data data.csv --show-transpiled ``` ```diff Compiling: strategy.pine... --- Transpiled JavaScript --- let opsv2_len = ctx.new_var("opsv2_len", 14); let opsv2_src = ctx.new_var("opsv2_src", opsv2_close); let opsv2_mySma = ctx.new_var("opsv2_mySma", ctx.call("sma@L4:C8", opsv2_sma, opsv2_src, opsv2_len)); ctx.call("plot@L6:C0", opsv2_plot, opsv2_mySma, { opsv2_color: opsv2_color.opsv2_red }); ----------------------------- Running backtest: 506 bars... + ✔ Done. ``` -------------------------------- ### Override input values with --input Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Pass overrides on the next run using --input key=value. The output shows the overridden values with a note like (overridden from 9). ```bash npm run opsv2 -- strategy.pine --data data.csv \ --input input_0=20 \ --input input_1=50 ``` ```diff === strategy.pine — Summary === ... Script Inputs: + input_0 "Fast Length" [integer] = 20 (overridden from 9) + input_1 "Slow Length" [integer] = 50 (overridden from 21) ``` -------------------------------- ### Run opsv2 with --compare-trades Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Compares the trade log from opsv2 against a TradingView trade export CSV. Checks trade count, entry price, exit price, profit, and exit timestamp per trade. ```bash npm run opsv2 -- strategy.pine --data data.csv --compare-trades ./tv_exports/trades.csv ``` -------------------------------- ### Run opsv2 with --compare-chart Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Compares indicator/plot columns from opsv2 against a TradingView chart export CSV. Rows are aligned by timestamp, columns matched by name with case-insensitive and positional fallbacks. ```bash npm run opsv2 -- strategy.pine --data data.csv --compare-chart ./tv_exports/chart_data.csv ``` -------------------------------- ### Chart Data FAIL output Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Output when values exceed tolerance. Lists mismatched rows with timestamps and deviations. ```diff - Chart Data: FAIL Rows compared : 506 - Mismatched : 3 Max deviation : - SMA_20↔SMA_20: 5.230e-2 (exceeds tolerance 0.0001) - First 3 mismatch(es): - [2024-03-15T10:00:00.000Z] SMA_20↔SMA_20 opsv2=148.3200 tv=148.3723 Δ=5.23e-2 - [2024-03-16T10:00:00.000Z] SMA_20↔SMA_20 opsv2=149.1100 tv=149.1641 Δ=5.41e-2 - [2024-03-17T10:00:00.000Z] SMA_20↔SMA_20 opsv2=149.8800 tv=149.9330 Δ=5.30e-2 - ...and 0 more (see report JSON) ``` -------------------------------- ### Run opsv2 with --out-comparison Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Writes comparison_report.json to the specified directory. If --out-dir is also set, that takes priority. If neither is set, no file is written — the console output is always printed regardless. ```bash npm run opsv2 -- strategy.pine --data data.csv \ --compare-chart ./tv_exports/chart_data.csv \ --out-comparison ./reports ``` -------------------------------- ### Extract inputs with jq after --dry-run Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Pipe the dry-run JSON to jq to extract just the inputs for a UI to render. The id values are what --input expects. ```bash npm run opsv2 -- strategy.pine --data data.csv --dry-run 2>/dev/null | jq '.inputs' ``` -------------------------------- ### Chart Data PASS output Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Output when values are within tolerance. Shows rows compared, mismatched count, and max deviation. ```diff + Chart Data: PASS Rows compared : 506 Mismatched : 0 Max deviation : + SMA_20↔SMA_20: 2.910e-5 ``` -------------------------------- ### Check folder layout compliance before commit Source: https://github.com/be-thomas/openpinescript/blob/main/CONTRIBUTING.md Shell script to verify that every top-level folder contains only version folders and no loose files. Silence means compliant; otherwise it prints a VIOLATION message. ```bash for d in */; do d=${d%/} case "$d" in node_modules|dev-docs) continue;; esac bad=$(find "$d" -mindepth 1 -maxdepth 1 -type d -not -name '.*' \ -exec basename {} \; | grep -vxE 'v[1-5]|common' | tr '\n' ' ') loose=$(find "$d" -mindepth 1 -maxdepth 1 -type f -not -name '.*' | wc -l | tr -d ' ') if [ -n "$bad" ] || [ "$loose" != 0 ]; then echo "VIOLATION $d: dirs=[$bad] loose_files=$loose" fi done ``` -------------------------------- ### Allowed top-level folder names Source: https://github.com/be-thomas/openpinescript/blob/main/CONTRIBUTING.md The only permitted child names for top-level folders. No other directory name or loose files are allowed at the top level. ```text v1 v2 v3 v4 v5 common ``` -------------------------------- ### Comparison report JSON structure Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Structure of the comparison report. overall_match is 'pass' when all active sections pass, 'fail' when all fail, 'partial' when mixed, and 'skip' when no comparison was run. ```json { "overall_match": "partial", "tolerance_used": 0.0001, "timestamp": "2026-03-15T10:00:00.000Z", "chart_data": { "status": "pass", "rows_compared": 506, "mismatched_rows": 0, "max_deviation": { "SMA_20↔SMA_20": 0.00005 }, "mismatches": [] }, "trades": { "status": "fail", "total_tv_trades": 38, "total_opsv2_trades": 37, "discrepancies": [ { "trade_id": 37, "issue": "missing_in_opsv2" }, { "trade_id": 42, "issue": "exit_price_mismatch", "tv_price": 45000.50, "opsv2_price": 45001.00, "detail": "deviation: 0.500000" } ] }, "summary": { "status": "pass", "net_profit_delta_percent": 0.0, "mismatches": [] } } ``` -------------------------------- ### Output chart: --out-chart Source: https://github.com/be-thomas/openpinescript/blob/main/CLI-Usage.md Writes a time-series CSV containing OHLCV candle data plus one column per plot() call. The command and its success output are shown together. ```bash npm run opsv2 -- strategy.pine --data data.csv --out-chart ./results/chart.csv ``` ```diff Compiling: strategy.pine... Running backtest: 506 bars... + ✔ Done. + ✔ Chart → ./results/chart.csv ``` -------------------------------- ### n (Bar Index) Source: https://github.com/be-thomas/openpinescript/blob/main/spec/v2/v2.md The n variable is an integer series representing the exact chronological position of the current bar relative to the start of the available dataset. The numbering is zero-based; the oldest historical bar yields an n value of 0, incrementing by 1 on each subsequent bar transition. ```APIDOC ## n (Bar Index) ### Description The n variable is an integer series representing the exact chronological position of the current bar relative to the start of the available dataset. The numbering is zero-based; the oldest historical bar yields an n value of 0, incrementing by 1 on each subsequent bar transition. ### Type Integer series ### Usage Accessible directly in the global namespace. ### Notes - The modern bar_index variable is not recognized in v2; use n instead. - The value increments by 1 on every bar transition. ``` -------------------------------- ### Run test suite with npm test Source: https://github.com/be-thomas/openpinescript/blob/main/docs/common/CONFORMANCE.md Executes the full test suite. The source reports 2,396 tests passing across 87 files with none failing. ```bash npm test ``` -------------------------------- ### Run strategy backtest with CLI Source: https://github.com/be-thomas/openpinescript/blob/main/README.md Use this command to run a Pine Script strategy backtest from the command line, specifying the script, data file, and output directory. The --json flag produces structured output. See the full CLI reference for more options. ```bash npm run opsv2 -- strategy.pine --data data.csv --out-dir ./results --json ``` -------------------------------- ### Run a single test suite or watch mode Source: https://github.com/be-thomas/openpinescript/blob/main/tests/v2/README.md Run a single suite with npx vitest run, or watch with npm run test:watch. ```bash npx vitest run tests/v2/lexer/lexer.test.ts ``` ```bash npm run test:watch ``` -------------------------------- ### Run a Pine script against CSV data Source: https://github.com/be-thomas/openpinescript/blob/main/README.md Executes a Pine script (e.g., examples/v1/sma_crossover.pine) against a CSV of bars using the opsv2 command. ```bash npm run opsv2 -- examples/v1/sma_crossover.pine --data mock_data/common/AAPL_mock.csv ``` -------------------------------- ### Math Basics Functions Source: https://github.com/be-thomas/openpinescript/blob/main/spec/v2/v2.md A suite of mathematical functions available in the global namespace for basic arithmetic and trigonometric operations. These functions are hardcoded and optimized in native code. ```APIDOC ## Math Basics Functions ### Description A suite of mathematical functions available in the global namespace for basic arithmetic and trigonometric operations. These functions are hardcoded and optimized in native code. ### Functions - abs - acos - asin - atan - ceil - cos - exp - floor - log - log10 - max - min - pow - round - sign - sin - sqrt - tan ### Usage Call directly by name, e.g., `abs(x)`, `max(a, b)`. ``` -------------------------------- ### Strategy Order Placement & Exits Source: https://github.com/be-thomas/openpinescript/blob/main/spec/v2/v2.md Strategy-specific commands for order placement and exit management. These are namespaced under the strategy prefix. ```APIDOC ## Strategy Order Placement & Exits ### Description Strategy-specific commands for order placement and exit management. These are namespaced under the strategy prefix. ### Functions - strategy.entry - strategy.exit - strategy.order - strategy.cancel - strategy.cancel_all - strategy.close - strategy.close_all ### Usage Call with the strategy prefix, e.g., `strategy.entry(id, direction, qty)`, `strategy.exit(id, from_entry, qty)`. ``` -------------------------------- ### Colors and Constants Source: https://github.com/be-thomas/openpinescript/blob/main/spec/v2/v2.md Built-in color constants and the color() function for casting variables to graphical colors. These are available in the global scope without a color.* prefix. ```APIDOC ## Colors and Constants ### Description Built-in color constants and the color() function for casting variables to graphical colors. These are available in the global scope without a color.* prefix. ### Constants - red - green - lime - white - blue - purple ### Functions - color(value) - Casts a variable to a graphical color. ### Usage Use constants directly, e.g., `plot(close, color=red)`. Use `color()` to convert values. ``` -------------------------------- ### Utility Functions Source: https://github.com/be-thomas/openpinescript/blob/main/spec/v2/v2_progress.md Utility functions for handling na values, conditionals, and string conversion. ```APIDOC ## Utility Functions ### Description Utility functions for handling na values, conditionals, and string conversion. ### Functions - `na(x)` - Returns true if x is na. - `nz(x)` - Replaces na with 0. - `iff(condition, a, b)` - Returns a if condition is true, else b. - `tostring(value)` - Converts value to string. - `fixnan(x)` - Replaces na with the previous non-na value. Context-aware, per call site. - `security(symbol, timeframe, expression)` - Deferred-thunk HTF sub-evaluation with no-lookahead alignment. ``` -------------------------------- ### Run quick parse with npm run parse Source: https://github.com/be-thomas/openpinescript/blob/main/grammar/common/README.md Parses inline "x=1\n" by default. Use -- file.pine to parse a file. ```bash npm run parse # parses inline "x=1\n" ``` ```bash npm run parse -- file.pine # parses a file ``` -------------------------------- ### Run emitted JavaScript in Node vm sandbox Source: https://github.com/be-thomas/openpinescript/blob/main/transpiler/common/transpiler-usage.md Runs transpiled JavaScript in a Node vm sandbox. Replace 'let' with 'var' to expose top-level bindings as sandbox properties. Access variables using the opsv2_ prefix. ```TypeScript import * as vm from "node:vm"; import { transpile } from "./transpiler/v2"; const pine = "a = 1\nb = 2\nc = a + b\n"; let js = transpile(pine); js = js.replace(/\blet\b/g, "var"); const sandbox: Record = Object.create(null); vm.createContext(sandbox); vm.runInContext(js, sandbox); console.log(sandbox.opsv2_a); // 1 console.log(sandbox.opsv2_b); // 2 console.log(sandbox.opsv2_c); // 3 ``` -------------------------------- ### Run conformance test with vitest Source: https://github.com/be-thomas/openpinescript/blob/main/conformance/common/golden.md Runs the golden test that compares engine output against TradingView data. ```bash npx vitest run conformance/tradingview_golden.test.ts ``` -------------------------------- ### Refresh frozen scanner anchors fixture Source: https://github.com/be-thomas/openpinescript/blob/main/docs/common/CONFORMANCE.md Run this command to refresh the frozen fixture used by scanner_anchors.test.ts. The collector refuses to write a fixture unless the bar TradingView reported matches the bar Binance served to the last decimal. ```bash node scripts/common/fetch-scanner-anchors.mjs # refresh the frozen fixture ``` -------------------------------- ### Generate parser with npm run generate:parser Source: https://github.com/be-thomas/openpinescript/blob/main/grammar/common/README.md Run from the project root to generate the parser for every version in the chain. Output is written to parser/v/generated/. Requires Node.js 20+ and the antlr-ng CLI. ```bash npm run generate:parser ``` -------------------------------- ### Color Constants Source: https://github.com/be-thomas/openpinescript/blob/main/spec/v2/v2_progress.md Color constants and functions for creating and modifying colors. ```APIDOC ## Color Constants ### Description Color constants and functions for creating and modifying colors. ### Constants - `red`, `green`, `blue`, `white`, `black`, etc. ### Functions - `color.new(color, transparency)` - Creates a new color with transparency. - `color.rgb(red, green, blue)` - Creates a color from RGB components. ``` -------------------------------- ### compileScript(source: string, opts?): { js, version, profile } Source: https://github.com/be-thomas/openpinescript/blob/main/transpiler/common/transpiler-usage.md Compiles Pine Script source and returns the JavaScript code along with the resolved version and profile. Useful when you need the version information. ```APIDOC ## compileScript(source: string, opts?): { js, version, profile } ### Description Compiles Pine Script source and returns the JavaScript code along with the resolved version and profile. Useful when you need the version information. ### Method Function ### Endpoint `compileScript(source: string, opts?): { js, version, profile }` ### Parameters - **source** (string) - Required - Pine Script source code. - **opts** (object) - Optional - Options object. May include `version` to force a specific Pine version. ### Returns - **js** (string) - JavaScript source code. - **version** (number) - Resolved Pine version. - **profile** (object) - Profile information. ### Errors - Throws `Error` with message `Parsing failed with N error(s)` if the source does not parse. - Throws `UnimplementedVersionError` if a script declares a version that is not implemented. ``` -------------------------------- ### Time & Date Functions Source: https://github.com/be-thomas/openpinescript/blob/main/spec/v2/v2.md Functions for accessing time and date information of the current bar. These are available in the global namespace. ```APIDOC ## Time & Date Functions ### Description Functions for accessing time and date information of the current bar. These are available in the global namespace. ### Functions - dayofmonth - dayofweek - hour - minute - month - second - time - timestamp - weekofyear - year ### Usage Call directly by name, e.g., `year`, `month`, `dayofmonth`. ``` -------------------------------- ### ANTLR v3 Grammar for PineScript v2 Source: https://github.com/be-thomas/openpinescript/blob/main/lexer/v2/README.md Reference grammar defining all tokens for PineScript v2. Includes operators, keywords, literals, identifiers, whitespace, and internal structural tokens. Used as the specification for the lexer implementation. ```antlr COND : '?' ; COND_ELSE : ':' ; OR : 'or' ; AND : 'and' ; NOT : 'not' ; EQ : '==' ; NEQ : '!=' ; GT : '>' ; GE : '>=' ; LT : '<' ; LE : '<=' ; PLUS : '+' ; MINUS : '-' ; MUL : '*' ; DIV : '/' ; MOD : '%' ; COMMA : ',' ; ARROW : '=>' ; LPAR : '(' ; RPAR : ')' ; LSQBR : '[' ; RSQBR : ']' ; DEFINE : '=' ; IF_COND : 'if' ; IF_COND_ELSE : 'else' ; BEGIN : '|BEGIN|' ; END : '|END|' ; ASSIGN : ':=' ; FOR_STMT : 'for' ; FOR_STMT_TO : 'to' ; FOR_STMT_BY : 'by' ; BREAK : 'break' ; CONTINUE : 'continue' ; LBEG : '|B|' ; LEND : '|E|' ; PLEND : '|PE|' ; INT_LITERAL : ( '0' .. '9' )+ ; FLOAT_LITERAL : ( '.' DIGITS ( EXP )? | DIGITS ( '.' ( DIGITS ( EXP )? )? | EXP ) ); STR_LITERAL : ( '"' ( ESC | ~ ( '\\' | '\n' | '"' ) )* '"' | '\'' ( ESC | ~ ( '\\' | '\n' | '\'' ) )* '\'' ); BOOL_LITERAL : ( 'true' | 'false' ); COLOR_LITERAL : ( '#' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT | '#' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ); ID : ( ID_LETTER ) ( ( '\.' )? ( ID_BODY '\.' )* ID_BODY )? ; ID_EX : ( ID_LETTER_EX ) ( ( '\.' )? ( ID_BODY_EX '\.' )* ID_BODY_EX )? ; INDENT : '|INDENT|' ; LINE_CONTINUATION : '|C|' ; EMPTY_LINE_V1 : '|EMPTY_V1|' ; EMPTY_LINE : '|EMPTY|' ; WHITESPACE : ( ' ' | '\t' | '\n' )+ ; fragment ID_BODY : ( ID_LETTER | DIGIT )+ ; fragment ID_BODY_EX : ( ID_LETTER_EX | DIGIT )+ ; fragment ID_LETTER : ( 'a' .. 'z' | 'A' .. 'Z' | '_' ) ; fragment ID_LETTER_EX : ( 'a' .. 'z' | 'A' .. 'Z' | '_' | '#' ) ; fragment DIGIT : ( '0' .. '9' ) ; fragment ESC : '\\' . ; fragment DIGITS : ( '0' .. '9' )+ ; fragment HEX_DIGIT : ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' ) ; fragment EXP : ( 'e' | 'E' ) ( '+' | '-' )? DIGITS ; Tokens : ( COND | COND_ELSE | OR | AND | NOT | EQ | NEQ | GT | GE | LT | LE | PLUS | MINUS | MUL | DIV | MOD | COMMA | ARROW | LPAR | RPAR | LSQBR | RSQBR | DEFINE | IF_COND | IF_COND_ELSE | BEGIN | END | ASSIGN | FOR_STMT | FOR_STMT_TO | FOR_STMT_BY | BREAK | CONTINUE | LBEG | LEND | PLEND | INT_LITERAL | FLOAT_LITERAL | STR_LITERAL | BOOL_LITERAL | COLOR_LITERAL | ID | ID_EX | INDENT | LINE_CONTINUATION | EMPTY_LINE_V1 | EMPTY_LINE | WHITESPACE ); ``` -------------------------------- ### Cross-Resolution & Utilities Functions Source: https://github.com/be-thomas/openpinescript/blob/main/spec/v2/v2.md Utility functions for cross-resolution data, condition handling, and data transformation. Available in the global namespace. ```APIDOC ## Cross-Resolution & Utilities Functions ### Description Utility functions for cross-resolution data, condition handling, and data transformation. Available in the global namespace. ### Functions - alertcondition - cross - crossover - crossunder - fixnan - heikinashi - iff - kagi - linebreak - na - nz - offset - pointfigure - renko - security - tickerid - tostring ### Usage Call directly by name, e.g., `cross(series1, series2)`, `security(symbol, timeframe, expression)`. ``` -------------------------------- ### transpile() basic usage Source: https://github.com/be-thomas/openpinescript/blob/main/transpiler/common/transpiler-usage.md Transpiles Pine Script source to JavaScript. The Pine version is inferred from the //@version annotation, defaulting to v1 if absent. Throws an Error with message 'Parsing failed with N error(s)' if parsing fails. ```TypeScript import { transpile } from "./transpiler/v2"; const js = transpile("x = 1 + 2 * 3\n"); // => "let opsv2_x = 1 + 2 * 3;\n" ``` -------------------------------- ### Math Functions Source: https://github.com/be-thomas/openpinescript/blob/main/spec/v2/v2_progress.md Mathematical functions for arithmetic, rounding, and trigonometric operations. ```APIDOC ## Math Functions ### Description Mathematical functions for arithmetic, rounding, and trigonometric operations. ### Functions - `abs(x)` - Absolute value. - `ceil(x)` - Rounds up to the nearest integer. - `floor(x)` - Rounds down to the nearest integer. - `round(x)` - Rounds to the nearest integer. - `sign(x)` - Returns the sign of x (1, -1, or 0). - `max(a, b)` - Returns the maximum of two values. - `min(a, b)` - Returns the minimum of two values. - `pow(a, b)` - Raises a to the power of b. - `sqrt(x)` - Square root. - `exp(x)` - Exponential function. - `log(x)` - Natural logarithm. - `log10(x)` - Base-10 logarithm. - `cos(x)` - Cosine. - `sin(x)` - Sine. - `tan(x)` - Tangent. - `acos(x)` - Arccosine. - `asin(x)` - Arcsine. - `atan(x)` - Arctangent. - `avg(a, b)` - Average of two values. ``` -------------------------------- ### Strategy Risk Management Source: https://github.com/be-thomas/openpinescript/blob/main/spec/v2/v2.md Strategy-specific commands for risk management. These are namespaced under the strategy.risk prefix. ```APIDOC ## Strategy Risk Management ### Description Strategy-specific commands for risk management. These are namespaced under the strategy.risk prefix. ### Functions - strategy.risk.allow_entry_in - strategy.risk.max_cons_loss_days - strategy.risk.max_drawdown - strategy.risk.max_intraday_filled_orders - strategy.risk.max_intraday_loss - strategy.risk.max_position_size ### Usage Call with the strategy.risk prefix, e.g., `strategy.risk.max_position_size(size)`. ``` -------------------------------- ### Plotting & Visuals Source: https://github.com/be-thomas/openpinescript/blob/main/spec/v2/v2_progress.md Functions for plotting data and adding visual elements to charts. ```APIDOC ## Plotting & Visuals ### Description Functions for plotting data and adding visual elements to charts. ### Functions - `plot(series)` - Plots a series on the chart. - `plotshape(series, style, location)` - Plots a shape. - `plotchar(series, char, location)` - Plots a character. - `hline(price)` - Draws a horizontal line. - `bgcolor(color)` - Sets background color. - `barcolor(color)` - Sets bar color. - `fill(series1, series2, color)` - Fills between two series. - `plotbar(open, high, low, close)` - Plots bars. - `plotarrow(series)` - Plots arrows. - `plotcandle(open, high, low, close)` - Plots candles. ``` -------------------------------- ### Time & Date Functions Source: https://github.com/be-thomas/openpinescript/blob/main/spec/v2/v2_progress.md Functions for extracting date and time components from bar timestamps. ```APIDOC ## Time & Date Functions ### Description Functions for extracting date and time components from bar timestamps. ### Functions - `year(time)` - Year component. - `month(time)` - Month component. - `dayofmonth(time)` - Day of month. - `dayofweek(time)` - Day of week. - `hour(time)` - Hour component. - `minute(time)` - Minute component. - `second(time)` - Second component. - `weekofyear(time)` - Week of year. - `time` - Current bar time. - `timestamp(y, m, d, h, min, s)` - Creates a timestamp from components. UTC, 1-indexed month. ``` -------------------------------- ### Generate log harness with npx tsx Source: https://github.com/be-thomas/openpinescript/blob/main/conformance/common/golden.md Regenerates the v5/ harnesses from v3 and v4 sources. Only needed after editing a harness. ```bash npx tsx scripts/common/make-log-harness.ts ``` -------------------------------- ### transpile(source: string, opts?): string Source: https://github.com/be-thomas/openpinescript/blob/main/transpiler/common/transpiler-usage.md Transpiles Pine Script source code into JavaScript. The Pine version is determined by the //@version annotation or can be forced via options. Throws an error if parsing fails. ```APIDOC ## transpile(source: string, opts?): string ### Description Transpiles Pine Script source code into JavaScript. The Pine version is determined by the //@version annotation or can be forced via options. Throws an error if parsing fails. ### Method Function ### Endpoint `transpile(source: string, opts?): string` ### Parameters - **source** (string) - Required - Pine Script source code. - **opts** (object) - Optional - Options object. May include `version` to force a specific Pine version. ### Returns - **string** - JavaScript source code (ES-like: `let`, `function`, etc.). ### Errors - Throws `Error` with message `Parsing failed with N error(s)` if the source does not parse. - Throws `UnimplementedVersionError` if a script declares a version that is not implemented. ### Example ```ts import { transpile } from "./transpiler/v2"; const js = transpile("x = 1 + 2 * 3\n"); // => "let opsv2_x = 1 + 2 * 3;\n" ``` ``` -------------------------------- ### Plotting Vectors Functions Source: https://github.com/be-thomas/openpinescript/blob/main/spec/v2/v2.md Functions for plotting data on the chart. These are available in the global namespace without any prefix. ```APIDOC ## Plotting Vectors Functions ### Description Functions for plotting data on the chart. These are available in the global namespace without any prefix. ### Functions - plot - plotarrow - plotbar - plotcandle - plotchar - plotshape ### Usage Call directly by name, e.g., `plot(series)`, `plotshape(series, title, style)`. ``` -------------------------------- ### Built-in Variables Source: https://github.com/be-thomas/openpinescript/blob/main/spec/v2/v2_progress.md Built-in variables available in Pine Script v2, including price series, bar index, and bar state. ```APIDOC ## Built-in Variables ### Description Built-in variables available in Pine Script v2, including price series, bar index, and bar state. ### Variables - `open` (series) - Opening price of the current bar. - `high` (series) - Highest price of the current bar. - `low` (series) - Lowest price of the current bar. - `close` (series) - Closing price of the current bar. - `volume` (series) - Volume of the current bar. - `n` (integer) - Zero-based bar index. Also exposed as `bar_index`. - `barstate.ishistory` (bool) - True if the current bar is a historical bar. - `barstate.isrealtime` (bool) - True if the current bar is a real-time bar. - `barstate.isnew` (bool) - True if the current bar is a new bar. - `barstate.islast` (bool) - True if the current bar is the last bar in the chart. ```