Indicator · Pine Script v6 · On the chart

Monte Carlo Lab

by jayadevrana

Monte Carlo Lab calculates and visualizes simulated performance variations for an Exponential Moving Average crossover strategy directly on the price chart.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code162
Settings6inputs
LicenceMPL-2.0
Last update4 days ago26 Oct 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

162 lines of Pine Script v6 from scripts/monte-carlo.pine.txt, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

monte-carlo.pine.txt
//@version=6
indicator("Monte Carlo Lab", overlay = true)

// 1. Settings
fastLen = input.int(20, "Fast average")
slowLen = input.int(50, "Slow average")
atrMult = input.float(2.0, "Stop = ATR x", step = 0.5)
rr      = input.float(2.0, "Target = R x", step = 0.5)
sims    = input.int(200, "Alternative histories to run", minval = 20, maxval = 500)
seed    = input.int(42, "Random seed")

// 2. The strategy whose luck we are about to question.
// ta.* calls belong at the top level, evaluated on every bar.
atr  = ta.atr(14)
fast = ta.ema(close, fastLen)
slow = ta.ema(close, slowLen)
long = ta.crossover(fast, slow)
plot(fast, "Fast", color.aqua)
plot(slow, "Slow", color.orange)

// 3. Every trade, recorded by hand as an R multiple. One open trade at a
// time, tracked in three plain variables, so a loser is -1 R and a winner
// is +rr R by construction. No engine, no cash, no commission guesswork.
var float entry = na
var float stop  = na
var float targ  = na
var array<float> rs = array.new<float>()
opened  = false
hitStop = false
hitTarg = false
if na(entry)
    if long and atr > 0
        entry := close
        stop  := close - atrMult * atr
        targ  := close + atrMult * atr * rr
        opened := true
else
    if low <= stop
        array.push(rs, -1.0)
        entry := na
        hitStop := true
    else if high >= targ
        array.push(rs, rr)
        entry := na
        hitTarg := true
plotshape(opened, "Entry", shape.triangleup, location.belowbar, color.teal)
plotshape(hitTarg, "Target", shape.triangledown, location.abovebar, color.green)
plotshape(hitStop, "Stop", shape.xcross, location.abovebar, color.red)

// 4. A reproducible random number generator (Pine has none).
// The state lives in a one-slot array: a function may not assign to a global.
var array<int> rngBox = array.new_int(1, seed)
nextRand() =>
    st = (1103515245 * array.get(rngBox, 0) + 12345) % 2147483648
    array.set(rngBox, 0, st)
    math.abs(st) / 2147483648.0

// 5. One alternative history: the same trades, dealt in a different order.
// Fisher-Yates is the only correct way to shuffle a list, and it is four lines.
// We return the two things we care about: where it finished, and how bad it got.
shuffledRun(src) =>
    n = array.size(src)
    work = array.copy(src)
    for i = n - 1 to 1
        j = math.floor(nextRand() * (i + 1))
        tmp = array.get(work, i)
        array.set(work, i, array.get(work, j))
        array.set(work, j, tmp)
    run = 0.0
    peak = 0.0
    dd = 0.0
    for i = 0 to n - 1
        run += array.get(work, i)
        peak := math.max(peak, run)
        dd := math.max(dd, peak - run)
    [run, dd]

// 6. Two tables: the numbers, and a histogram of how painful the ride was
var table t = table.new(position.bottom_left, 2, 7, border_width = 1)
row(r, a, b, bg) =>
    table.cell(t, 0, r, a, text_color = color.white, text_size = size.normal,
      bgcolor = color.new(color.gray, 20), text_halign = text.align_left)
    table.cell(t, 1, r, b, text_color = color.white, bgcolor = bg,
      text_size = size.normal)
var table h = table.new(position.middle_right, 3, 16, border_width = 1)
blocks(count, pk) =>
    w = int(math.round(24.0 * count / math.max(pk, 1)))
    s = ""
    // a Pine for-loop with a start above its end counts DOWNWARDS,
    // so an empty bin would print two blocks instead of none
    if w > 0
        for i = 1 to w
            s += "█"
    s

// 7. Run the simulation on the last bar
if barstate.islast and array.size(rs) > 20
    n = array.size(rs)
    // the real, historical order: this is the curve every backtest shows you
    realRun = 0.0
    realPeak = 0.0
    realDd = 0.0
    for i = 0 to n - 1
        realRun += array.get(rs, i)
        realPeak := math.max(realPeak, realRun)
        realDd := math.max(realDd, realPeak - realRun)
    finals = array.new<float>()
    worst  = array.new<float>()
    for s = 0 to sims - 1
        [f, d] = shuffledRun(rs)
        array.push(finals, f)
        array.push(worst, d)

    // 8. Bin the drawdowns. This is the distribution that actually matters,
    // because the drawdown is the part of a backtest you have to live through.
    ddMax = math.max(array.max(worst), realDd)
    binW  = ddMax / 12
    counts = array.new_int(12, 0)
    for i = 0 to sims - 1
        b = math.min(11, math.floor(array.get(worst, i) / binW))
        array.set(counts, b, array.get(counts, b) + 1)
    pk = array.max(counts)
    table.cell(h, 0, 0, "max DD", text_color = color.white,
      bgcolor = color.new(color.blue, 20), text_size = size.small)
    table.cell(h, 1, 0, "HOW OFTEN", text_color = color.white,
      bgcolor = color.new(color.blue, 20), text_size = size.small)
    table.cell(h, 2, 0, "", bgcolor = color.new(color.blue, 20))
    for b = 0 to 11
        lo = b * binW
        mine = realDd >= lo and realDd < lo + binW
        table.cell(h, 0, 12 - b, str.tostring(lo, "#0.0") + "R",
          text_color = color.white, bgcolor = color.new(color.gray, 30),
          text_size = size.tiny)
        table.cell(h, 1, 12 - b, blocks(array.get(counts, b), pk),
          text_color = lo > realDd ? color.red : color.teal,
          bgcolor = color.new(color.black, 0), text_size = size.tiny,
          text_halign = text.align_left)
        table.cell(h, 2, 12 - b, mine ? "<- your backtest" : "",
          text_color = color.yellow, bgcolor = color.new(color.black, 0),
          text_size = size.tiny, text_halign = text.align_left)

    // 9. The numbers underneath
    sortedD = array.copy(worst)
    array.sort(sortedD)
    d50 = array.get(sortedD, math.floor(sims * 0.50))
    d95 = array.get(sortedD, math.floor(sims * 0.95))
    spread = array.max(finals) - array.min(finals)
    row(0, "MONTE CARLO", str.tostring(sims) + " orders of " +
      str.tostring(n) + " trades", color.new(color.blue, 20))
    row(1, "your backtest ended", str.tostring(realRun, "#.0") + "R",
      color.new(color.orange, 25))
    row(2, "best minus worst ending", str.tostring(spread, "#.00") + "R",
      color.new(color.gray, 25))
    row(3, "your backtest's drawdown", str.tostring(realDd, "#.0") + "R",
      color.new(color.orange, 25))
    row(4, "median drawdown", str.tostring(d50, "#.0") + "R",
      color.new(color.gray, 25))
    row(5, "95th percentile drawdown", str.tostring(d95, "#.0") + "R",
      color.new(color.red, 25))
    row(6, "times worse than you saw",
      str.tostring(d95 / math.max(realDd, 0.01), "#.00") + "x",
      color.new(color.red, 25))

Overview

Monte Carlo Lab records trade outcomes using ATR-based stop-loss and target levels in terms of R-multiples. On the final bar, the indicator executes Fisher-Yates shuffling simulations using a custom random number generator to model alternative trade sequence orderings. It displays summary metrics and a drawdown distribution histogram in on-screen dashboard tables. Users can configure moving average lengths, risk-reward ratios, stop multipliers, simulation counts, and random seeds.

Details

Published by

jayadevrana on GitHub

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingbacktestingema-crossoverpine-scriptpine-script-v6pinescriptrsitechnical-analysistrading-automationtrading-indicators

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Fast averageint20fastLen
Slow averageint50slowLen
Stop = ATR xfloat2.0atrMult
Target = R xfloat2.0rr
Alternative histories to runint200sims
Random seedint42seed
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

228 stars

TradersPost Trading Checklist is an overlay indicator that evaluates a suite of popular technical conditions for long and short trade setups. It checks session-anchored VWAP, fast and slow EMA alignments and crosses, 200 SMA, RSI overbought or oversold conditi

Indicator v6 Screeners & dashboardsTrend
Updated 3 months ago · None stated GitHub repository of TradersPost Trading Checklist
92 stars

This indicator plots five moving averages of a chosen source on the price chart, defaulting to EMA lengths 10, 20, 30, 40 and 50. The user can switch the average type to SMA, WMA or HMA and recolor each line. Wide translucent glows sit under the lines, and sof

Indicator v5 TrendMoving averages
Updated 2 months ago · Custom licence GitHub repository of Moon Dev Rainbow MA Ribbon 10-50

EMA Ribbon Overlay

by iamrichardD
57 stars

Calculates exponential moving averages for fast, pivot, and slow lengths along with optional 50, 100, and 200 simple moving average context lines. It visualizes bullish and bearish ribbon fills on the main price chart alongside MACD calculations to generate ea

Indicator v6 TrendMoving averages
Updated 1 year ago · Apache-2.0 GitHub repository of EMA Ribbon Overlay
53 stars

This indicator analyzes historical candle direction and price range over a configurable lookback window to gauge market trend. It categorizes trend direction using candle count, price range sum, or both. Signals are filtered using a Simple Moving Average to en

Indicator v6 TrendOscillators & momentum
Updated 2 months ago · MPL-2.0 GitHub repository of Candle Counter + MA + RSI + Mode
43 stars

This indicator evaluates market momentum and risk by calculating trend metrics and volatility stats, displaying them in an on-chart table pane. It measures short-term and long-term trend strength via two MACD configurations built on three customizable EMA leng

Indicator v5 TrendVolatility & bands
Updated 1 year ago · None stated GitHub repository of Trend Strength & Volatility

Market Monitor - 15m

by chris-c-thomas
14 stars

Market Monitor - 15m is a directional bias chart overlay designed for 15-minute intraday chart analysis. It calculates a triple exponential moving average ribbon with EMA cloud shading, session VWAP with multiplier bands, prior day levels, a 30-minute opening

Indicator v6 TrendMoving averages
Updated 6 months ago · MIT GitHub repository of Market Monitor - 15m

More Moving averages scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers