Metadata-Version: 2.4
Name: pineforge-codegen
Version: 0.6.5
Summary: PineScript v6 to C++ transpiler that targets the pineforge-engine runtime.
Project-URL: Homepage, https://github.com/pineforge-4pass/pineforge-codegen-oss
Project-URL: Issues, https://github.com/pineforge-4pass/pineforge-codegen-oss/issues
Project-URL: Engine, https://github.com/pineforge-4pass/pineforge-engine
Author-email: PineForge <luis@4pass.com.tw>
License: PineForge Codegen — License
        ============================
        
        Copyright 2025 PineForge <luis@4pass.com.tw>
        
        This software is made available under the **PolyForm Noncommercial License
        1.0.0** (reproduced in full below), as modified by the two supplemental
        sections that follow. In case of any conflict, the supplemental sections
        ("Additional Permission" and "Commercial Use") control over the base license.
        
        Required Notice: Copyright 2025 PineForge (https://github.com/pineforge-4pass/pineforge-codegen-oss)
        
        
        Additional Permission — Personal Trading
        ----------------------------------------
        
        Notwithstanding the limitation to noncommercial purposes in the base license,
        the licensor grants you, free of charge, an additional license to use the
        software for **Personal Trading**, and Personal Trading is hereby a permitted
        purpose under the base license — including its Copyright License, Distribution
        License, Changes and New Works License, and Patent License.
        
        **Personal Trading** means use of the software by a natural person to research,
        develop, backtest, and execute trades in financial instruments, where:
        
          (a) the trades are placed for that same natural person's own account; and
        
          (b) the trades are funded solely by that person's own capital.
        
        Personal Trading does **not** include, and this Additional Permission does
        **not** cover:
        
          (1) managing, advising on, or trading capital belonging to any other person
              or entity, whether or not for a fee;
        
          (2) use by, for, or on behalf of any company, fund, partnership, or other
              organization, including use by an individual in the course of work for
              such an organization;
        
          (3) embedding the software, or output generated by it, into any product or
              service made available to others; or
        
          (4) operating any hosted, software-as-a-service, or otherwise public-facing
              service that uses the software.
        
        The use described in (1)–(4) is Commercial Use.
        
        
        Commercial Use
        --------------
        
        Any use that is not a permitted purpose under the base license and is not
        covered by the Additional Permission above — including the uses listed in
        (1)–(4) of that section — requires a separate commercial license from the
        licensor.
        
        To obtain a commercial license, contact: luis@4pass.com.tw
        
        
        ================================================================================
        The remainder of this file is the verbatim text of the PolyForm Noncommercial
        License 1.0.0. Where it differs from the supplemental sections above, the
        supplemental sections control.
        ================================================================================
        
        
        # PolyForm Noncommercial License 1.0.0
        
        <https://polyformproject.org/licenses/noncommercial/1.0.0>
        
        ## Acceptance
        
        In order to get any license under these terms, you must agree
        to them as both strict obligations and conditions to all
        your licenses.
        
        ## Copyright License
        
        The licensor grants you a copyright license for the
        software to do everything you might do with the software
        that would otherwise infringe the licensor's copyright
        in it for any permitted purpose.  However, you may
        only distribute the software according to [Distribution
        License](#distribution-license) and make changes or new works
        based on the software according to [Changes and New Works
        License](#changes-and-new-works-license).
        
        ## Distribution License
        
        The licensor grants you an additional copyright license
        to distribute copies of the software.  Your license
        to distribute covers distributing the software with
        changes and new works permitted by [Changes and New Works
        License](#changes-and-new-works-license).
        
        ## Notices
        
        You must ensure that anyone who gets a copy of any part of
        the software from you also gets a copy of these terms or the
        URL for them above, as well as copies of any plain-text lines
        beginning with `Required Notice:` that the licensor provided
        with the software.  For example:
        
        > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
        
        ## Changes and New Works License
        
        The licensor grants you an additional copyright license to
        make changes and new works based on the software for any
        permitted purpose.
        
        ## Patent License
        
        The licensor grants you a patent license for the software that
        covers patent claims the licensor can license, or becomes able
        to license, that you would infringe by using the software.
        
        ## Noncommercial Purposes
        
        Any noncommercial purpose is a permitted purpose.
        
        ## Personal Uses
        
        Personal use for research, experiment, and testing for
        the benefit of public knowledge, personal study, private
        entertainment, hobby projects, amateur pursuits, or religious
        observance, without any anticipated commercial application,
        is use for a permitted purpose.
        
        ## Noncommercial Organizations
        
        Use by any charitable organization, educational institution,
        public research organization, public safety or health
        organization, environmental protection organization,
        or government institution is use for a permitted purpose
        regardless of the source of funding or obligations resulting
        from the funding.
        
        ## Fair Use
        
        You may have "fair use" rights for the software under the
        law. These terms do not limit them.
        
        ## No Other Rights
        
        These terms do not allow you to sublicense or transfer any of
        your licenses to anyone else, or prevent the licensor from
        granting licenses to anyone else.  These terms do not imply
        any other licenses.
        
        ## Patent Defense
        
        If you make any written claim that the software infringes or
        contributes to infringement of any patent, your patent license
        for the software granted under these terms ends immediately. If
        your company makes such a claim, your patent license ends
        immediately for work on behalf of your company.
        
        ## Violations
        
        The first time you are notified in writing that you have
        violated any of these terms, or done anything with the software
        not covered by your licenses, your licenses can nonetheless
        continue if you come into full compliance with these terms,
        and take practical steps to correct past violations, within
        32 days of receiving notice.  Otherwise, all your licenses
        end immediately.
        
        ## No Liability
        
        ***As far as the law allows, the software comes as is, without
        any warranty or condition, and the licensor will not be liable
        to you for any damages arising out of these terms or the use
        or nature of the software, under any kind of legal claim.***
        
        ## Definitions
        
        The **licensor** is the individual or entity offering these
        terms, and the **software** is the software the licensor makes
        available under these terms.
        
        **You** refers to the individual or entity agreeing to these
        terms.
        
        **Your company** is any legal entity, sole proprietorship,
        or other kind of organization that you work for, plus all
        organizations that have control over, are under the control of,
        or are under common control with that organization.  **Control**
        means ownership of substantially all the assets of an entity,
        or the power to direct its management and policies by vote,
        contract, or otherwise.  Control can be direct or indirect.
        
        **Your licenses** are all the licenses granted to you for the
        software under these terms.
        
        **Use** means anything you do with the software requiring one
        of your licenses.
License-File: LICENSE
Keywords: backtesting,pinescript,trading,tradingview,transpiler
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: Free for non-commercial use
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial
Requires-Python: >=3.11
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == 'dev'
Description-Content-Type: text/markdown

# pineforge-codegen

> PineScript v6 → C++ transpiler that emits against the [pineforge-engine](https://github.com/pineforge-4pass/pineforge-engine) runtime.

[![PyPI](https://img.shields.io/pypi/v/pineforge-codegen.svg)](https://pypi.org/project/pineforge-codegen/)
[![Python](https://img.shields.io/pypi/pyversions/pineforge-codegen.svg)](https://pypi.org/project/pineforge-codegen/)
[![License](https://img.shields.io/badge/license-PolyForm%20Noncommercial%201.0.0-orange.svg)](LICENSE)
[![Personal use](https://img.shields.io/badge/personal%20trading-free-22c55e.svg)](#license)

A pure-Python library that turns a PineScript v6 strategy into a complete C++
source file you can compile against the [`pineforge-engine`](https://github.com/pineforge-4pass/pineforge-engine)
runtime — a deterministic native backtester validated **trade-for-trade against
TradingView** (231/232 corpus parity).

It is **source-available and free for personal trading** — research, backtest,
and trade your own account with your own capital at no cost. See
[License](#license) for the line between personal and commercial use.

- **Pure Python, zero runtime dependencies** — one function, `transpile()`.
- **Fails loud, never silent** — a support checker rejects Pine the engine can't
  faithfully run *before* codegen, with a `file:line:col` error. You never get
  silently-wrong C++.
- First complete PineScript v6 → C++ transpiler with a real support checker (to
  our knowledge).

---

## Install

```bash
pip install pineforge-codegen
```

Requires Python ≥ 3.11. No runtime dependencies.

From source (development / contributing):

```bash
git clone https://github.com/pineforge-4pass/pineforge-codegen-oss.git
cd pineforge-codegen-oss
pip install -e ".[dev]"
```

## Quick start

```python
from pineforge_codegen import transpile

pine = """
//@version=6
strategy("SMA cross", overlay=true)
fast = ta.sma(close, 10)
slow = ta.sma(close, 30)
if ta.crossover(fast, slow)
    strategy.entry("long", strategy.long)
if ta.crossunder(fast, slow)
    strategy.close("long")
"""

cpp = transpile(pine)
print(cpp)          # complete C++ source string
```

The output `#include`s `<pineforge/engine.hpp>`, `<pineforge/ta.hpp>`, … and
compiles into a `.so` exposing the engine's documented C-ABI.

## Usage

### The `transpile()` function

```python
transpile(
    pine_source: str,
    *,
    check_support: bool = True,   # run the support checker before codegen
    filename: str = "<input>",    # name used in error locations
) -> str
```

Returns the generated C++ source as a string. Raises
`pineforge_codegen.errors.CompileError` on any unsupported construct or syntax
error.

### Transpile a file to a `.cpp`

```python
from pathlib import Path
from pineforge_codegen import transpile

pine = Path("strategy.pine")
cpp = transpile(pine.read_text(), filename=pine.name)   # filename → better errors
Path("strategy.generated.cpp").write_text(cpp)
```

### Handle unsupported features

The support checker raises a `CompileError` with the exact source location
instead of emitting broken C++:

```python
from pineforge_codegen import transpile
from pineforge_codegen.errors import CompileError

try:
    transpile('//@version=6\nindicator("x")\n')
except CompileError as e:
    print(e)
    # <input>:2:1: indicator() declarations are not supported; PineForge runs strategies only.

try:
    transpile('//@version=6\nstrategy("x")\n'
              'x = request.financial("AAPL", "REV", "FQ")\n')
except CompileError as e:
    print(e)
    # <input>:3:22: request.financial(...) is not supported.
```

Pass `filename=` so the location points back at the user's file:

```python
transpile(src, filename="my_strategy.pine")
# raises e.g.  my_strategy.pine:12:5: ...
```

### Skip the support checker

`check_support=False` bypasses the gate (intended only for tests of legacy
fixtures — it can produce C++ the engine won't accept):

```python
cpp = transpile(src, check_support=False)
```

### Trace intermediate expressions (`@pf-trace`)

A `// @pf-trace name=expr` comment makes the engine emit `name`'s per-bar value
in the backtest report — useful for debugging parity against TradingView:

```python
pine = """
//@version=6
strategy("traced")
// @pf-trace rsi=ta.rsi(close, 14)
e = ta.ema(close, 20)
if close > e
    strategy.entry("L", strategy.long)
"""
cpp = transpile(pine)   # emitted on_bar tail records `rsi` each bar
```

### Advanced: run the pipeline stages directly

`transpile()` is a thin wrapper over five passes. Drive them yourself to inspect
tokens, the AST, or the analyzer context:

```python
from pineforge_codegen import (
    Lexer, Parser, Analyzer, CodeGen,
    extract_pf_trace_pragmas, check_support_or_raise,
)

src = open("strategy.pine").read()
pragmas = extract_pf_trace_pragmas(src)
tokens  = Lexer(src, filename="strategy.pine").tokenize()
ast     = Parser(tokens, source=src, filename="strategy.pine").parse()
check_support_or_raise(ast, filename="strategy.pine")
ctx     = Analyzer(ast, filename="strategy.pine").analyze()
ctx.pf_trace_pragmas = pragmas
cpp     = CodeGen(ctx).generate()
```

## How it works

`transpile()` runs five passes, in order:

```
pine source
  │
  ├─ 1. extract_pf_trace_pragmas   // @pf-trace comments pulled out first
  ├─ 2. Lexer → Parser             token stream → Pine v6 AST
  ├─ 3. support_checker            reject anything the engine can't run faithfully
  ├─ 4. Analyzer                   type inference, scope resolution, TA bookkeeping
  └─ 5. CodeGen                    → C++ source string
```

## Compile & run against the engine

The emitted C++ targets the C-ABI in `<pineforge/pineforge.h>`. To build and run
a strategy:

```bash
# Get the runtime (Apache-2.0) next to this repo
git clone https://github.com/pineforge-4pass/pineforge-engine.git
```

Follow the engine's [`tutorial/`](https://github.com/pineforge-4pass/pineforge-engine/tree/main/tutorial)
to build `libpineforge.a`, compile your transpiled `.cpp` into a strategy `.so`,
feed it OHLCV, and read back the closed-trade list. The codegen version must
target a matching engine ABI (see [`VERSION`](VERSION)).

Prefer no local build? A hosted transpile API + MCP server is available so AI
agents can transpile and backtest for you — see <https://www.pineforge.dev>.

## Running tests

```bash
pip install -e ".[dev]"
pytest
```

The pure-transpiler suite is fast (< 1 s) and has no native dependencies — it
checks token streams, parse trees, analyzer output, and canonical C++ strings
without invoking a C++ compiler.

Opt-in compile checks (`tests/test_compile_smoke.py`, `tests/test_compile_corpus.py`)
run `g++ -fsyntax-only` on transpiled C++ against the engine headers. They
auto-detect a sibling `../pineforge-engine` checkout, or set the path explicitly:

```bash
export PINEFORGE_ENGINE_INCLUDE=/path/to/pineforge-engine/include
pytest
```

Without an engine checkout these tests skip cleanly, so CI stays green.

## License

Source-available under the [PolyForm Noncommercial License 1.0.0](LICENSE), with
two supplemental terms (the `LICENSE` file is the controlling text):

- **Personal Trading exception** — free to research, backtest, and trade for your
  own account with your own capital.
- **Commercial use** — companies, funds, managing third-party capital, embedding
  in a product, or operating a hosted / public-facing service requires a
  commercial license.

Competing hosted services are not permitted under the noncommercial terms. This
is source-available, not OSI open source.

### Buying a commercial license

Commercial licenses are available — flexible terms for funds, products, and
hosted/embedded use. Email **luis@4pass.com.tw** with your use case for a quote.
