Documentation

Everything you need to get started with Foresight.

Overview

Foresight is a backtesting engine for TradingView Pine Script strategies and indicators. It compiles your Pine Script, runs it against OHLCV data on your own machine, and lets you debug it, test it out of sample and optimise its parameters. No TradingView subscription is needed once the script and the data it uses are loaded.

Foresight comes in two forms on one account. The web app runs in your browser with nothing to install: the same engine, compiled to WebAssembly, runs in the browser tab on your own machine, with the script editor, debugger, replay, repaint detection, optimizer and walk-forward, and a connection for AI clients. The Windows desktop app adds multi-instrument runs, the full statistics panel, the built-in data manager with more data providers, and a local MCP server and Python client.

Web app: quick start

  1. Sign in and open foresight.trading/app. The engine downloads once and then runs inside the tab.
  2. Open Data and add price history: drop in a CSV file (or a folder of them), or use Fetch from to download crypto history straight from an exchange. Data is kept in that browser, on your computer.
  3. In Develop, paste your Pine script into the editor. It is checked as you type; press Run (Ctrl+Enter).
  4. Drag an input to re-run. Debug records every variable on every bar, with breakpoints and Replay. Research has the optimizer, walk-forward testing and the overfitting checks.
  5. Save project writes the script, its inputs and the data it uses to one file you can open again later, or on another computer.

Scripts that import a TradingView library need that library's source added under Data › Script libraries. To drive the web app from an AI client, see Connect an AI agent.

The rest of this page describes the Windows desktop app; the web app has the same engine, arranged as Develop, Debug, Research and Data.

Desktop app: quick start

  1. Launch Foresight.
  2. Open a Pine Script file with File → Open Script, or drag a .pine file onto the window. File → New Script (Ctrl+N) starts an empty one to paste into.
  3. Load market data with File → Open Data (any OHLCV CSV), or fetch it in Data mode.
  4. The backtest runs as soon as both are loaded. The chart, the result bar and the Results tab fill in.
  5. Open the Parameters tab and drag a slider: the strategy re-runs as you drag. Start the optimizer when you want Foresight to search for you.

The three modes

The switch in the title bar (or Ctrl+1, Ctrl+2, Ctrl+3) changes what the window is arranged for.

ModeWhat it is for
DataYour data library: fetch from providers, import CSV files, choose what to load.
DebugOne run, examined closely: step through bars, watch variables, set breakpoints, replay history, check for repainting.
AnalyzeMany runs: the optimizer, walk-forward testing, broker models and the results table. Foresight starts here.

Loading Scripts

Use File → Open Script to open a .pine file, or drag one onto the window. The script is compiled immediately; anything wrong is marked in the editor and listed in the Problems tab.

Your 8 most recently opened scripts are under File → Recent Scripts. File → Save Project keeps the script, its data and your results together in one .frs file.

Loading Data

Use File → Open Data to load an OHLCV CSV file: columns for timestamp, open, high, low, close and volume. The file is read where it is; it is not uploaded anywhere.

To download data instead, switch to Data mode. Recent data files are under File → Recent Data.

Data mode

Data mode (title bar, Ctrl+1, or File → Data) is where you browse, fetch and manage market data. It has three columns: your library on the left, a chart of the selected dataset in the middle, and Browse & Fetch on the right. Fetched datasets are stored on your machine. What each provider offers (instruments, history, regions) differs; OANDA and Tiingo need your own credentials.

Fetching data

Workflow

  1. Pick a provider in the left pane: Binance, Kraken, Bybit, OKX, Dukascopy, OANDA, Tiingo or Cboe.
  2. Type in the search box to find an instrument. All / Downloaded narrows the list to what you already have.
  3. Each instrument shows a row of timeframe squares: 1m, 5m, 15m, 1H, 4H, D and W. Only the timeframes that provider offers are available.
  4. Select the timeframes you want and press Fetch. Progress is shown while it downloads.

Import CSV adds a file of your own to the library alongside fetched data.

Using your library

  • Double-click a downloaded timeframe square to load it and switch to Analyze.
  • Select several squares and press Load Selected to load more than one instrument (see Multiple Instruments).
  • The right-hand pane lists each timeframe you hold with the date it was last fetched or imported and a bar showing the dates it covers. The remove icon deletes a dataset after asking you to confirm.

Run preparation

When a script needs data that is not loaded (another symbol, another timeframe), Foresight lists what is missing and where it can come from before the run; the Problems tab shows the same rows with a Resolve button. Source choices you save are reused. Data is never silently substituted. You can always use your own OHLCV CSV files instead.

Data Providers

Binance & Kraken

Crypto market data. Instruments, history and regional access depend on the provider; Kraken serves only about the most recent 720 bars of a timeframe.

Bybit & OKX

BTC, ETH, SOL, XRP, DOGE, ADA and LTC against USDT, spot and perpetual, at 1m, 5m, 15m, 1H, 4H, daily and weekly.

Dukascopy

The catalog and available history are shown in the app. 5m, 15m, 4H and weekly bars are built from Dukascopy's 1m, 1H and daily data.

OANDA & Tiingo

Both use your own provider credentials. Tiingo covers stocks and ETFs at daily bars only.

Cboe

Daily OHLC for VIX, VIX9D and VIX3M. There is no volume, and Foresight leaves it missing; it does not invent one.

Foresight does not download data from TradingView or Yahoo Finance, and has no fundamental, economic or yield feeds.

Running a Backtest

Once a script and data are loaded the backtest runs by itself, and it re-runs whenever you move a parameter slider or recompile the script. The result bar shows the headline figures for the current run, its repaint check, and Details ▸, which opens the full statistics and trade list.

Trade Report

In Debug mode the Trades tab lists every trade of the current run; click a trade to land on its bar. In Analyze mode, Details ▸ or a double-click on any row of the Results table opens the same list for that parameter set, beside its statistics.

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

CSV Export

Export to CSV above the trade list saves every trade, with all the columns above, to a file you choose. The Results table has its own Export CSV for the optimizer's results.

Statistics

The full statistics view covers CAGR and total return, annual and monthly returns, Sharpe, Sortino, Calmar and Ulcer ratios, downside and annualised volatility, maximum drawdown, win rate, profit factor, buy-&-hold return and alpha, total and per-trade commission (cost drag), expectancy with a t-statistic and 95% confidence interval, average win and loss, winning and losing streaks, and a monthly returns heatmap.

Debugger & Replay

Switch to Debug mode to examine a run after it has finished. Nothing is re-simulated to show you a value: the debugger reads what the run recorded, and a value it did not record is shown as not recorded, never guessed.

  • Step through bars. The transport row above the chart moves the playhead to the previous or next bar, or the previous or next trade entry. Left / Right step one bar; with Shift, ten.
  • See values. Hover a variable in the editor to see its value on the playhead's bar. The Watch panel keeps chosen values in view as you step.
  • Breakpoints. Click the editor's gutter or press F9 on a line. Breakpoints work on the finished run, so you can add one afterwards and see every bar where it would have hit, in the Breakpoints tab.
  • Replay. Tick Replay (or press R) and the script is re-run as of the playhead's bar, seeing only the data it had then; later bars are dimmed. Space plays and pauses, at 2 to 80 bars a second.

Repaint check

A strategy repaints when its historical signals use information that was not available at the time, most often a higher-timeframe value read before that bar had closed. Foresight runs the strategy as written and again seeing only what existed on each bar, and compares the two. The verdict is shown in the result bar; in Debug mode check repaint runs it on demand and go to divergence jumps to the first bar where the runs differ. The Results table has a Repaint column, and a right-click on a row checks that entry. A clean verdict means no repainting was found on this data. It is not a judgement of the strategy.

Execution Realism

The same strategy can look very different depending on how fills are simulated. Foresight re-runs any backtest under three execution models, chosen in the Broker tab in Analyze mode, in the result bar, or with set_broker_model:

ModelBehaviour
TradingView, the defaultTradingView's Strategy Tester rules: the model our comparisons with TradingView are run under. Spreads come from the data as they are.
RealisticExits become live on the bar after entry, the stop wins when stop and target both fall inside one bar, trailing stops follow the close, each instrument has a minimum spread, and calc_on_every_tick, calc_on_order_fills and process_orders_on_close are switched off.
PessimisticEverything Realistic does, plus random adverse slippage on every fill.

An edge that holds under Realistic and Pessimistic is much less likely to be an artifact of the fill model. A strategy that only profits under TradingView's rules is leaning on optimistic same-bar fills. Surviving a stricter model is still not evidence of a live edge. The current Windows build labels these three TV (parity), Strict and Adversarial, and set_broker_model takes tv, strict and adversarial. Changing the model clears the optimizer's results, because they were scored under the old one.

Multiple Instruments

Foresight can run one strategy across several instruments at once, to see whether an edge holds beyond a single chart. In Data mode, select the datasets you want and press Load Selected; each instrument gets its own tab above the chart and is backtested on its own data.

In Analyze mode, tick Multi-instrument opt to have the optimizer score a parameter set across the whole basket, and choose how the scores are combined: average, worst, geometric mean, or average minus standard deviation. This scales to large universes, for example a daily scan across the S&P 500.

This is different from cross-symbol request.security() inside one script (a script reading another ticker's series), which is also supported: see Supported Features.

Optimizer

The Optimize tab in Analyze mode searches the parameter space for you. It does not try every combination: the default is differential evolution, and under Search algorithm (advanced) you can choose L-SHADE, multi-modal DE or a Sobol sweep instead. You can also set the score it optimises, an iteration limit, a random seed and minimum-trade guards.

Controls

  • Start optimization begins the search. While it runs, the result bar shows the iteration and best score so far, with a Stop button.
  • Stop optimization halts it and keeps what was found.
  • Reset clears the results back to the row for the current parameters (it asks first). Your parameter values are not changed.

The optimizer uses all your CPU cores.

Parameter Controls

The Parameters tab, beside Code, has a slider for each numeric input.* in your script (a text box for string inputs).

  • Drag a slider and the backtest re-runs as you drag.
  • The ON box decides whether the optimizer may vary a parameter. Untick it to hold the parameter at its slider value. At least one must stay on.
  • Ranges come from your script's input() definitions. Click a range to give the optimizer different limits.

Results

The Results tab keeps the best 500 different parameter sets the optimizer has tried, best first, plus a row for your current parameters. Two sets count as the same result when nine in ten of their in-sample trades open in the same direction within a bar of each other; of such a pair only the higher-scoring one is kept, so the table shows distinct alternatives rather than hundreds of near-copies of the winner. Each row has its score, Sharpe ratio, win rate, maximum drawdown and trade count, plus an out-of-sample score when a validation window is set, a robustness score and a repaint verdict. The status bar counts every set tried; a saved project keeps the best 50 rows.

  • Click a row to select that parameter set.
  • Double-click a row for its full statistics and trade list.
  • Right-click a row to analyze its robustness, check it for repainting, or open it in Debug mode.
  • Click a column header to sort. Export CSV saves the table; File → Save Project keeps the results with the session.

Walk-forward testing

Optimizing on the same data you judge the result on flatters every strategy. The Walk Forward tab in Analyze mode optimizes on one stretch of history (in-sample), tests the chosen parameters on the stretch that follows (out-of-sample), then rolls both forward and repeats. Set the in-sample start, the out-of-sample start and end and the iterations per fold, then press Run walk-forward. The out-of-sample results are the ones to believe.

Overfitting & robustness

  • PBO (in the Results tab, after at least 16 optimizer trials) estimates the probability of backtest overfitting: how often the best in-sample parameter set turns out below average out of sample.
  • Analyze robustness re-runs the top results with each input nudged, and fills the Robust column. An edge that vanishes when a length changes by one was probably fitted to noise.
  • The result bar shows how many trials the best result was chosen from, and a deflated Sharpe ratio that discounts for that choice.

Script Editor

The Code tab is a Pine Script editor with syntax highlighting, completion and signature help as you type, and live diagnostics: errors and warnings are underlined where they occur and listed in the Problems tab, where a click takes you to the line.

  • Hover a name to see its type and where it is declared. In Debug mode, hovering a variable shows its value on the current bar.
  • F12 goes to a definition. On an import line it opens the library's source, read-only.
  • Several scripts can be open at once; click the file name to switch between them.
  • Font size has four presets in the toolbar, and Ctrl + mouse wheel zooms freely. Wrap toggles line wrapping.
  • If a script uses something Foresight does not support (for example request.financial()), the diagnostic names it. Nothing is skipped silently.

Keyboard Shortcuts

F1 shows this list in the app.

ShortcutAction
Ctrl+1 / Ctrl+2 / Ctrl+3Data / Debug / Analyze mode
Ctrl+NNew script
Ctrl+SSave script
Ctrl+Z / Ctrl+YUndo / redo
Ctrl+F / Ctrl+HFind / find and replace
F3 / Shift+F3Next / previous match
Ctrl+GGo to line
F12Go to definition
Ctrl+/Toggle comment
Ctrl+DSelect word, then add the next occurrence
Ctrl+Shift+DDuplicate line or selection
Alt+Up / Alt+DownMove lines
Alt+ClickAdd a cursor
Ctrl+Shift+[ / ]Fold / unfold
F9Toggle a breakpoint
Left / RightDebug: step a bar (Shift: ten)
R / SpaceDebug: toggle Replay / play and pause

Automation — MCP & Python API

The research and backtesting command core can also be driven programmatically, either as MCP tools or from the Python client. Some desktop-only interactions remain GUI workflows.

MCP

The desktop app is its own MCP server (version 1.1.9 and later); nothing else needs installing. To connect an AI assistant, tick Let the AI assistants on this PC use Foresight in the installer, or in the app choose ? → Connect an AI Agent and press Connect beside Claude Desktop, Claude Code, Cursor, VS Code or Windsurf. Restart the assistant afterwards.

For any other MCP client, add this entry to its MCP configuration (the dialog shows it with your install path and has a Copy button):

{
  "mcpServers": {
    "foresight": {
      "command": "C:\\Program Files\\Foresight\\Foresight.exe",
      "args": ["--mcp"]
    }
  }
}

The assistant opens Foresight when it needs it, and an agent can then 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, in the window you can see. Foresight stays open when the assistant closes.

Python

The Python client is currently a source/developer interface. It is not bundled with the Windows installer or published on PyPI, and it is not needed for MCP. When working from the source tree, install its python directory, then connect to a running engine, or pass autospawn=True to have it start one headless.

from foresight import Client

c = Client()                      # connect to a running Foresight
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 broadly, including:

  • Core strategy.* functions for entries, exits, closes and order sizing
  • Common ta.* indicators including SMA, EMA, RSI, MACD, Bollinger Bands, ATR and SuperTrend
  • 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() — including a ta.* call or computed expression as the third argument (multi-timeframe analysis)
  • Cross-symbol request.security() (one script reading a different ticker's series — the referenced symbol's data must be loaded or fetchable)
  • Lower-timeframe / intrabar request.security_lower_tf() at minute granularity when matching finer-timeframe data is loaded or fetchable
  • Library imports (import Author/Library/N) — vendored or local library trees

Not yet supported

  • request.financial() / economic data feeds

File Formats

Data (CSV)

Foresight reads standard OHLCV CSV files. Expected columns: timestamp (or date), open, high, low, close, volume. A CSV exported from TradingView or a similar tool should load as it is. Data fetched in Data mode is stored in the same format.

Scripts (.pine)

Standard Pine Script v5 and v6, as used on TradingView. Copy a strategy or indicator from TradingView's editor into a new script (Ctrl+N) or a .pine file and run it as it is.