Documentation

Everything you need to get started with Foresight.

Overview

Foresight is a native C++ backtesting engine for TradingView Pine Script strategies. It transpiles your Pine Script, runs it against OHLCV data locally, and lets you optimise strategy parameters using differential evolution — all without a browser or TradingView subscription.

The application is a standalone Windows desktop app with an integrated script editor, interactive charts, and a built-in data manager for downloading market data.

Quick Start

  1. Launch Foresight.
  2. Open a Pine Script file via File → Open Script (or drag-and-drop a .pine file onto the window).
  3. Load market data via File → Open Data (any OHLCV CSV), or use the Data Manager to download data directly.
  4. The backtest runs automatically. Results appear in the charts and statistics panels.
  5. Adjust parameters with the sliders and enable the optimizer to search for better configurations.

Loading Scripts

Use File → Open Script or press Ctrl+O to open a .pine file. You can also drag-and-drop a script file directly onto the application window. The script is compiled immediately and any errors are shown in the editor with red line markers.

Your 8 most recently opened scripts appear under File → Recent Scripts for quick access.

Loading Data

Use File → Open Data or press Ctrl+Shift+O to load an OHLCV CSV file. Foresight accepts standard CSV format with columns for timestamp, open, high, low, close, and volume. Your data stays entirely on your machine.

Alternatively, use the Data Manager to download data directly from supported providers. Recent data files are available under File → Recent Data.

Data Manager

Open the Data Manager from File → Data Manager. It provides a built-in way to browse, download, and manage market data from multiple providers — no external tools or subscriptions needed. Downloaded datasets are stored locally and can be auto-updated in the background.

Browse & Download

The Browse tab lets you search for symbols across all supported providers and download historical data.

Workflow

  1. Select a provider from the dropdown (Yahoo Finance, TradingView, or Dukascopy).
  2. Choose a timeframe (1m, 5m, 15m, 1H, 4H, Daily, Weekly). Only timeframes supported by the selected provider are shown.
  3. Type in the search box to filter symbols by name, ticker, or asset class.
  4. Click a symbol to select it, then click Download — or simply double-click a symbol to start the download immediately.
  5. A progress bar shows download status in real time.

Downloaded data is saved as a CSV and added to your My Data library automatically.

My Data Library

The My Data tab shows all datasets you have downloaded.

ColumnDescription
SymbolTicker symbol (e.g. BTCUSD, AAPL)
ProviderData source (Yahoo, TradingView, Dukascopy)
TimeframeBar interval (1m through Weekly)
Last UpdatedWhen the dataset was last refreshed
SizeFile size on disk
Auto-updateToggle to enable background updates

Interactions

  • Double-click a row to load that dataset into the current backtest and close the Data Manager.
  • Right-click a row for a context menu: Load into Backtest, Update Now, or Remove.

Auto-Update

Enable the auto-update checkbox on any dataset to keep it current in the background. Foresight checks for staleness automatically:

  • Intraday (1m, 5m, 15m): updates if older than 4 hours
  • Hourly (1H, 4H): updates if older than 1 day
  • Daily / Weekly: updates if older than 3 days

Updates are incremental — only new bars since the last update are downloaded and appended.

Data Providers

Yahoo Finance

Stocks, ETFs, indices, crypto, forex. Supports 1m, 5m, 15m, 1H, Daily, and Weekly timeframes. No 4H support.

TradingView

All asset classes. Supports all timeframes including 4H.

Dukascopy

Forex pairs, metals, indices, and crypto. Supports all timeframes. Downloads up to 10-15 years of history. Data is fetched from Dukascopy's CDN, decompressed, and resampled to your chosen timeframe.

Running a Backtest

Once a script and data file are loaded, the backtest runs automatically. Results update in real time across all panels — charts, statistics, and the trades list. Adjust any parameter slider to re-run the backtest instantly with the new value.

Trade Report

The Trades tab shows a full breakdown of every trade the strategy executed. You can also access the trade report by double-clicking any entry in the results library — this opens a detailed stats view including the complete trade list for that parameter configuration.

ColumnDescription
#Trade number
TypeLong or Short
Entry DateEntry timestamp
Entry PriceFill price at entry
Exit DateExit timestamp
Exit PriceFill price at exit
P&LAbsolute profit or loss
P&L %Percentage return
BarsTrade duration in bars

Winning trades are shown in green, losing trades in red.

CSV Export

Click the Export button at the top of the Trades tab to save the full trade list as a CSV file. A native file dialog opens where you can choose the destination and filename. The exported CSV includes all columns from the trade report — suitable for further analysis in Excel, Python, or any spreadsheet tool.

Statistics & KPIs

The bottom panel displays key performance indicators at a glance:

MetricDescription
Total Return %Net strategy return over the data period
Sharpe RatioRisk-adjusted return (higher is better)
Win Rate %Percentage of trades that were profitable
Max Drawdown %Worst peak-to-trough equity decline
Profit FactorGross profit divided by gross loss
Trade CountTotal number of trades executed

Advanced statistics include CAGR and total return, annual/monthly returns, Sortino, Calmar and Ulcer ratios, downside and annualised volatility, buy-&-hold return and alpha, total and per-trade commission (cost drag), expectancy with a t-statistic and 95% confidence interval, average win/loss size, consecutive win/loss streaks, and a monthly returns heatmap.

Charts

Foresight provides several chart views, accessible as tabs in the main area:

  • Price / Equity — Candlestick chart with trade entry/exit markers (left) and equity curve (right).
  • Profit & Loss — Bar chart of per-trade P&L. Green bars for wins, red for losses.
  • Oscillators — Indicator plots (RSI, MACD, etc.) synchronised with the price chart.
  • Library Statistics — Heatmap of optimisation results across parameter space.
  • Trades — The full trade report table (see above).

Execution Realism

The same strategy can look very different depending on how honestly fills are simulated. Foresight lets you re-run any backtest under three execution models, selectable from the Broker panel (or programmatically via set_broker_model):

ModelBehaviour
TV (default)Matches TradingView's Strategy Tester semantics — the baseline used for golden-trade parity. Data spreads as-is.
StrictHonest execution: exits go live the next bar onward, stop-loss wins when both stop and target fall inside one bar, close-based trailing, a per-instrument spread floor, and flaky flags (e.g. calc_on_every_tick) normalised off.
AdversarialEverything Strict does, plus random adverse slippage on every fill.

If an edge holds up under Strict and Adversarial it is far less likely to be a fill-model artifact. A strategy whose profit only survives under TV is leaning on optimistic same-bar fills — Foresight surfaces that instead of hiding it.

Multiple Instruments

Foresight can load more than one instrument at a time and run the same strategy across all of them — useful for confirming that an edge generalises rather than fitting a single chart. Each instrument is backtested against its own data feed; results appear per-instrument and as a combined equity curve, and the optimizer can score across the whole basket so you tune for robustness instead of one lucky symbol. This scales to large universes — for example a daily scan across the entire S&P 500.

This is distinct from cross-symbol request.security() inside a single script (one script reading a different ticker's series), which is not yet supported — see Supported Features.

Differential Evolution Optimizer

Foresight uses differential evolution (DE) to search for optimal parameter configurations intelligently rather than testing every combination by brute force. The optimizer explores parameter space efficiently, converging on high-performing configurations in seconds.

Controls

  • Run — Start the optimisation. The button turns red and becomes Stop while running.
  • Stop — Gracefully halt the current run.
  • Reset — Clear results and restart from the current parameter values.
  • Multithreading — Enable to use all CPU cores. Shows thread count when active.

The optimizer displays the current iteration, population size, and best score in real time.

Parameter Controls

Each input.* parameter from your Pine Script appears as a slider in the left sidebar. Parameters can be toggled active (red — included in optimisation) or inactive (blue — held at the slider value).

  • Move a slider to set its value. The backtest re-runs instantly.
  • Uncheck a parameter to fix it at its current value during optimisation.
  • Parameter ranges are determined from your script's input() definitions.

Results Library

Every parameter configuration tested by the optimizer is stored in the results library. The library table shows the score, Sharpe ratio, win rate, max drawdown, and trade count for each result.

  • Click a row to select it and view its statistics.
  • Double-click a row to open a detailed view with the full trade report, equity curve, and monthly returns for that configuration.
  • Click column headers to sort results.
  • Use the toolbar buttons to Save / Load individual results or the entire library.

Script Editor

The built-in editor supports Pine Script syntax highlighting, error markers, and standard editing features. Compilation errors appear as red markers on the relevant line numbers — hover to see the error message.

  • Edit your script directly and the backtest updates on save.
  • Font size is adjustable (Normal, Medium, Large) from the editor toolbar.
  • If a script uses unsupported features (e.g. cross-symbol data feeds or library imports), a dialog lists them.

Keyboard Shortcuts

ShortcutAction
Ctrl+OOpen script
Ctrl+Shift+OOpen data file
Ctrl+SSave script
Ctrl+ZUndo
Ctrl+YRedo
Ctrl+FFind / Replace
Ctrl+GGo to line
Ctrl+/Toggle comment

Automation — MCP & Python API

Everything you can do in the GUI you can also drive programmatically, over one shared command core — either as MCP tools (for AI agents such as Claude) or from the Python client.

MCP

Foresight serves the Model Context Protocol on 127.0.0.1:17374. Point any MCP client at it and an agent can load sessions, run backtests, sweep and optimise parameters, run walk-forward validation, switch the execution model, and read back equity curves, trades and statistics — then edit the script and re-run in place.

Python

Install the client and connect to a running engine (or let it spawn one headless):

pip install foresight
from foresight import Client

c = Client()                      # connect to a running engine
c.load_session("strategy.pine", data_path="EURUSD_H1.csv")
stats = c.get_stats()             # -> dict (ntrade, profit_all, sharpe, ...)
close = c.get_series("close")     # -> numpy array, length = bar count
c.start_opt()                     # run the optimizer

OHLCV and result series move as binary numpy arrays in both directions — no JSON parsing for bulk data. The same client runs against the live GUI (watch results render) or fully headless via Foresight.exe --serve.

Supported Pine Script Features

Foresight supports Pine Script V5 and V6 including:

  • All strategy.* functions (entry, exit, close, order sizing)
  • All ta.* indicators (SMA, EMA, RSI, MACD, Bollinger Bands, ATR, SuperTrend, etc.)
  • math.* and str.* standard library functions
  • User-defined functions (UDFs) and methods
  • User-defined types (UDTs / structs)
  • Enums and switch expressions
  • For / for-in / while loops
  • Multi-assignment tuple returns
  • Ternary chains and conditional expressions
  • Drawing objects: label, line, box
  • Table functions
  • input.* parameters (int, float, bool, string, color, source, timeframe)
  • Series access with [] history operator
  • var and varip persistence
  • matrix<T> and map<K,V> collections
  • Higher-timeframe request.security() on the chart's own symbol — including a ta.* call or computed expression as the third argument (multi-timeframe analysis)

Not yet supported

  • Cross-symbol request.security() (referencing a different ticker inside one script — each script runs against a single data feed. To test across many symbols, load them as multiple instruments instead.)
  • request.security_lower_tf() and other lower-timeframe / intrabar request.* feeds
  • Custom library imports (import Author/Library/...)

File Formats

Data (CSV)

Foresight reads standard OHLCV CSV files. Expected columns: timestamp (or date), open, high, low, close, volume. Any CSV exported from TradingView, Yahoo Finance, or similar tools should work directly. The Data Manager downloads data in this format automatically.

Scripts (.pine)

Standard Pine Script V5/V6 files as used on TradingView. You can copy-paste a strategy from TradingView's editor into a .pine file and load it directly.