PineForge
An open-source C++17 engine for backtesting and forward execution, with PineScript support through code generation.
🌐 pineforge.dev · ☁️ Hosted MCP · 🐳 Docker MCP · 📦 Transpiler · 📖 C ABI docs · 🧪 Coverage map · 🔬 Benchmarks
Why PineForge
PineForge is a C++17 engine for backtesting and forward execution, with a C ABI for embedding. The engine has two layers:
- A generic kernel — a Pine-agnostic backtest and forward-execution state machine: order matching and fills, sizing, margin and settlement, the bar magnifier, indicator classes,
request.security(), time and session math. Some TradingView-shaped names survive in its archive, each ruled in ADR 0001 and held there byscripts/check_kernel_residuals.py. - A source-adapter parity runtime (
src/source/andsrc/compat/pine/,PineExecutionAdapter+PineStrategyHost) — maps Pine/TradingView execution semantics onto that kernel. This is where TradingView parity lives.
The separate PineForge compiler, pineforge-codegen, translates a PineScript v6 script into a C++ strategy that attaches the engine's Pine execution adapter (its releases 1.0.0, 1.0.1, 1.1.0, 1.2.0 and 1.3.0 do; 0.10.4 predates the adapter); it owns translation, not execution semantics. TradingView comparisons measure this Pine path under the tested configurations. The order model describes the current submodels and the remaining migration work; Architecture states the boundary.
- Proven, not promised. All 7,989 graded probes — 309 open reference strategies, 680 community-shared scripts and 61 probe scripts the maintainers wrote, on 18 market/timeframe lanes — grade against TradingView's own trade lists: 7,983 excellent, 6 strong, 0 below strong. The graded probes' TradingView trade lists hold 4,776,328 trades; 17 probes with TradingView-side defects are excluded.
- Open runtime. The engine and native live runner are Apache-2.0. The separately distributed PineForge compiler is source-available under the PineForge Source License 1.2 from its release 1.3.0 (release 1.2.0 keeps the PineForge Source License 1.1, and releases up to 1.1.0 keep the PolyForm Noncommercial terms they shipped with); personal trading is free, and commercial use requires a separate license; the capital in an account a proprietary-trading firm or funded-trader program provides or allocates, including a challenge, evaluation or simulated account, is investment capital. Public reference strategies, benchmarks and validation tooling are available in their respective repositories; the community-script test set is not redistributed.
- Fast. In-process, no interpreter: median 36× faster than PyneCore on the 200 strategies both engines time (100 corpus probes and 100 held-out private strategies), measured at engine
35db01c8on 2026-09-29 on an AWS c7a.8xlarge with PyneCore timed as a subprocess, its interpreter start-up included (PineForge runs a median 807k bars/s per strategy over its 201 slots with the bar magnifier on; method). Parameter sweeps re-run a loaded.sowith new inputs — no recompile, no fork. - Deterministic to the bit. Two runs with the same inputs produce identical trade lists.
- Yours to embed. 162
PF_APIdeclarations across six installed headers —pineforge.h's 106 (86 of the 97 runtime exports and up to 20 per-strategy functions a generated module defines), eleven more runtime declarations inexecution_observer.h,selected_window.handreport_sink.h(three, three and five),native_c_api.h's 43 native-host declarations andselected_window_plan.h's two planner declarations — an ABI that is append-only within a major version from 1.0 on. Call it from C, Python, Rust, Go, Node, Julia — or let an AI agent drive it over MCP.
Recorded outputs and their additional API declarations described here are part of 1.5.0.
1.6.1
was released on 2026-10-18, paired with
pineforge-codegen 1.6.1.
The release notes cover selected-window
contract revision 1.3-parity rather than 1.3 until a completeness proof
exists, preflight stage timings, the API documentation updates since 1.6.0,
and the CI and test updates since the release candidate.
For the 1.6.1 pair, regenerate strategy C++ and relink against that pair's
headers and archive. Published 1.3.0 download and installation examples below
remain pinned to that earlier pair.
Engine 1.6.1 (released without a hub image) declares selected-window
contract revision 1.3-parity through docker/run_json.py --capabilities-json:
it emits the four typed codes (strategy_value_invalid,
engine_command_value_invalid, report_result_invalid and
report_post_execution_failed), with parity with the 1.4.0 reference on tested
cases, and no completeness claim (the published 1.6.0 image declares 1.3).
capabilities.selected_window_contract_revisions is ["1.3-parity"] when the
runtime supports selected windows and [] otherwise.
From 1.6.2, the engine/codegen image advertises selected-window
contract revision 1.3 through docker/run_json.py --capabilities-json:
with the section-4 producers and manifest present and value ownership
complete, it emits the four typed codes (strategy_value_invalid,
engine_command_value_invalid, report_result_invalid and
report_post_execution_failed). A build declaring 1.3 pairs only with a
complete receipt; 1.3-parity remains the parity build's literal, and a
tuple holding both is invalid (the published 1.5.0 image declared
1.3-parity, earlier images carried no revision member; the published 1.6.0
image declared 1.3 without a completeness proof; and engine 1.6.1, released
without a hub image, declares 1.3-parity).
capabilities.selected_window_contract_revisions is ["1.3"] when the
runtime supports selected windows and [] otherwise; see the
capability table and
report schema.
The public contract for selected windows and walk-forward use
defines the supported CLI and C entry points, capability detection and stability rules.
Get a backtest in 60 seconds
With an AI agent (MCP, Docker only)
claude mcp add pineforge-backtest \
-- docker run --rm -i -v "$PWD:/work" ghcr.io/pineforge-4pass/pineforge-backtest-mcp:latest
For Cursor, which expands ${workspaceFolder}, or any MCP client (in Claude Desktop, put an absolute path in its place):
{
"mcpServers": {
"pineforge-backtest": {
"command": "docker",
"args": ["run", "--rm", "-i", "-v", "${workspaceFolder}:/work",
"ghcr.io/pineforge-4pass/pineforge-backtest-mcp:latest"]
}
}
}
Then ask: "Fetch BTC/USDT 15m for the last 90 days and backtest this strategy" — the container transpiles Pine → C++ with the bundled pineforge-codegen, compiles, runs, and hands the agent the trade list. The image is built on the pineforge-release image, which ships a released engine and codegen pair; its engine_info tool reports the image's version. Your Pine and data stay on your machine; only the Binance tools (fetch_binance_ohlcv, binance_symbols) call out, to Binance's public API. Mount a directory at /work; -i is required and -t must not be added (a TTY corrupts the JSON-RPC stream).
| Ask | Tool |
|---|---|
| "Fetch BTC/USDT 15m data for the last 30 days" | fetch_binance_ohlcv |
| "Backtest this SMA-cross strategy on that data" | backtest_pine |
| "Sweep fast 8–21 × slow 21–55, rank by net PnL" | backtest_pine_grid |
| "What broker overrides are available?" | list_engine_params |
Prefer zero install? The hosted server at mcp.pineforge.dev/mcp (Streamable HTTP, no key) backtests one configuration at a time on crypto OHLCV it fetches itself (seven venues; the free tier serves the last 365 days), metered per IP by a weekly backtest quota. The npm package @pineforge/backtest-mcp is the local server run from Node 20+ on the host; it runs each transpile and backtest in the pineforge-release image through your Docker daemon.
From source
git clone https://github.com/pineforge-4pass/pineforge-engine.git && cd pineforge-engine
python3 scripts/ci_verify.py release --build-dir build --jobs 4
bash tutorial/run.sh # MACD on BTC/USDT, end to end
python3 tutorial/run_stream.py # OHLCV warm-up → realtime trades
The shared local/CI verifier includes source guards, tests and installed-package smoke checks. Its ABI check links callers against both the current library and seven separately built, pinned historical libraries. Preparation uses local Git history and the configured compiler, fetching a pinned commit the clone lacks; see the ABI fixture guide (the README of the private fixture set settlement_cpp_abi) for repeated checks. The first run needs network (the verifier initialises the public corpus submodule itself; configure fetches Eigen when no system copy is found) and a full clone: a depth-1 clone fails the benchmark provenance row (CI guide). CTest itself stays offline.
Supported platforms: Linux x86_64 and arm64. From 1.8.0 the engine's release archives are built, and CI runs, for Linux only (linux-x86_64 and linux-aarch64 archives; no macOS archive). Other platforms build from source and are not tested or supported.
Prerequisites: CMake ≥ 3.16 to build (the verifier and ctest --test-dir need 3.20), a C++17 compiler whose standard library has floating-point std::to_chars (libstdc++ from GCC 11 or later, or libc++ 14 or later; CI builds with GCC on Ubuntu 24.04), Eigen 3.3+ (fetched automatically if absent), Python 3 for the tests (-DPINEFORGE_BUILD_TESTS=OFF -DPINEFORGE_BUILD_TUTORIAL=OFF for a library-only build). cmake --install build --prefix /usr/local installs lib/libpineforge.a and lib/libpineforge_kernel.a, include/pineforge/, and the find_package(PineForge) config.
Prebuilt library
The v1.3.0 release attaches the library prebuilt: pineforge-v1.3.0-linux-x86_64.tar.gz, pineforge-v1.3.0-linux-aarch64.tar.gz and pineforge-v1.3.0-macos-universal.tar.gz, each with a .sha256. Each unpacks to one directory holding what the install above writes (the two archives, include/pineforge/ and the find_package(PineForge) config) plus LICENSE, NOTICE and VERSION; point CMAKE_PREFIX_PATH at it. The package asks for Eigen 3.3+: install it on Linux, while the macOS tarball carries Eigen 3.4.0 (install guide).
Embedded in your own harness
#include <pineforge/pineforge.h>
#include <stdio.h>
int main(void) {
pf_strategy_t s = strategy_create(NULL);
pf_bar_t bars[] = { /* OHLCV ... */ };
pf_report_t r = {0};
run_backtest(s, bars, sizeof(bars)/sizeof(*bars), &r);
printf("%d trades, net %.2f\n", r.trades_len, r.net_profit);
report_free(&r);
strategy_free(s);
return 0;
}
Every PineForge-compiled strategy .so exports this same ABI, so one harness serves every module built against the same PF_ABI_VERSION (compare pf_abi_version() before a run). Build the harness against a module, or look the names up with dlopen/dlsym: -lpineforge alone defines no strategy_create, run_backtest or report_free. Worked examples for C, Python sweeps, Rust, multi-strategy and magnifier A/B are in the docs.
Lifecycle-aware compiled modules reset Pine variables, indicator/history buffers and the broker book before each batch run or strategy_stream_begin warmup. Inputs and runtime settings persist until changed; ticks within a stream continue its state. Regenerate and rebuild existing modules with current codegen and matching engine headers/archive to obtain this behavior; the internal C++ rebuild boundary is checked at compile/link time.
Three front doors
The engine can be driven three ways. All three run the same kernel, so for the same requests they match trigger, price fills, book lots and settle identically; what differs is who writes the strategy, who owns TradingView's quirks and, for C, the C++ capabilities the 1.0 C surface does not spell (the 1.0 C boundary table in the native engine guide).
1. PineScript, through codegen
Write Pine, transpile it, run the .so. The Pine adapter reproduces
TradingView's execution semantics on top of the kernel; this is the path the
validation scoreboard below measures.
This command block is for the published engine/codegen 1.3.0 pair. For 1.6.1, use the matching release tags linked above and regenerate and relink against that pair's headers and archive.
pip install "pineforge-codegen==1.3.0"
python3 -c "from pathlib import Path; from pineforge_codegen import transpile; Path('generated.cpp').write_text(transpile(Path('strategy.pine').read_text(), filename='strategy.pine'))"
c++ -std=c++17 -O2 -ffp-contract=off -shared -fPIC generated.cpp \
-Wl,--whole-archive /usr/local/lib/libpineforge.a -Wl,--no-whole-archive -o strategy.so
python3 scripts/run_strategy.py . --ohlcv tutorial/data/btcusdt_15m_7d.csv --no-trim-output # or drive it over the C ABI
Run it from the engine checkout, with strategy.pine there, after the cmake --install above (with a prebuilt tarball instead, add -I<its directory>/include and link its lib/libpineforge.a). Engine v1.3.0 pairs with pineforge-codegen 1.3.0, as v1.2.0 does with 1.2.0, v1.1.0 with 1.1.0, v1.0.1 with 1.0.1 and v1.0.0 with 1.0.0; codegen 0.10.4 emits C++ for engine v0.13.1, which the headers of v1.0.0, v1.0.1, v1.1.0, v1.2.0 and v1.3.0 no longer compile. No codegen release has a command-line entry point, so transpile through transpile(). The compile line above is for Linux; with Clang, add -fbracket-depth=1024. A macOS/Clang source build instead links -Wl,-force_load,/usr/local/lib/libpineforge.a. Linking the whole archive is what puts the runtime's C exports (pf_abi_version, the strategy_stream_* family) in the module; a script that uses matrix.* also needs Eigen's include directory.
2. C++, against the kernel
Subclass NativeStrategyHost, describe the run once, hand it bars. No Pine,
no codegen, no src/source. The complete file is
examples/native/hello_kernel.cpp —
the strategy half of it:
#include <pineforge/native_host.hpp>
class HelloKernel : public pineforge::NativeStrategyHost {
int bars_ = 0;
void on_native_run_begin() override { bars_ = 0; }
void on_native_bar(const pineforge::Bar&,
const pineforge::NativeDecisionContext&) override {
++bars_;
if (bars_ == 1) {
submit_market({pineforge::order_action::Transact{1.0}, "hello-long", ""});
} else if (bars_ == 3) {
submit_market({pineforge::execution::Flatten{}, "hello-flat", ""});
}
}
};
// configure_native(spec) applies one NativeRunSpec; run(bars, n) drives them;
// trade_count() / get_trade(i) read the closed rows back.
The other hosts under examples/native/ cover kernel
sizing and its fee reserve, anchored brackets on a price grid, trails in ticks,
a margin model with a real liquidation and an FX-curve roll, account risk
limits, calculation timing, higher-timeframe series, an auxiliary finer feed,
the open book lot by lot, per-bar broker-state hashes, and a kernel-recorded
report. Each is a CTest row in a build with -DPINEFORGE_BUILD_EXAMPLES=ON (the ci_verify.py release build above has it): ctest --test-dir build -R '^example_'.
3. C, against the same kernel
Hand the runtime a callback table and drive the kernel from any language with
a C FFI — no C++ in your own code. The complete file is
examples/native/hello_kernel_c.c; the
41 strategy_native_* functions (plus two strategy_configure_native_ext_*
functions) are declared in
include/pineforge/native_c_api.h and
summarised in Driving the kernel from C below.
#include <pineforge/pineforge.h>
pf_native_callbacks_v1 cb = {0};
cb.struct_size = (uint32_t)sizeof cb;
cb.version = PF_NATIVE_API_VERSION;
cb.user = &state;
cb.on_bar = on_bar; /* submit / replace / cancel from here */
pf_strategy_t s = strategy_native_host_create_v1(&cb);
strategy_configure_native_v1(s, &spec); /* or strategy_configure_native_ext_v1(s, &spec, &ext) */
strategy_native_run_v1(s, bars, n, &
