Pine Script (Lesson 14): Monte Carlo, Your Backtest Is One Sample

Pine Script course, lesson 14. Your backtest draws one equity curve, and you decide the strategy is good or bad from it. That line is a single sample. The same strategy, with exactly the same trades, could have produced thousands of different looking lines, and some of them would have made you quit.

This lesson builds a Monte Carlo laboratory in Pine: it records every closed trade as an R multiple, writes a linear congruential random generator (Pine has none), shuffles the trade list with Fisher-Yates, and replays two hundred alternative histories on your chart – then bins their drawdowns into a histogram and marks the bin your own backtest landed in.

It also prints the number that settles an argument you will see constantly online: best ending minus worst ending across all those orderings is 0.00R. Reordering a list of numbers cannot change their sum, so shuffling tells you nothing about your final profit. What it tells you about is the journey.

Then the real experiment in Python on 12,000 BTCUSDT 1h candles: 110 real trades, 37.27% win rate, +13.0R with a 10R drawdown. Across 10,000 reorderings the median worst drawdown was 11R, the 95th percentile 18R, and the worst ordering 32R – more than three times what the backtest showed. And resampling with replacement, which does question the result, finished at -11R at the 5th percentile and lost money in 19.18% of futures.

FREE CODE + CHART SNAPSHOTS (copy-paste ready)
Monte Carlo Lab (this lesson): https://jayadevrana.in/free-pine-script-indicators/monte-carlo/
All free Pine Script indicators: https://jayadevrana.in/free-pine-script-indicators/
GitHub: https://github.com/jayadevrana/free-pine-script-indicators

Pine Script course playlist: https://www.youtube.com/playlist?list=PLLXezQvH0Of0

What you’ll learn
– Writing a random number generator in Pine, and why its state must live in an array
– The Fisher-Yates shuffle in four lines
– Why shuffling cannot change your total, and what it does measure
– Bootstrapping: the test that does ask whether your edge was luck
– Sizing for the 95th percentile drawdown instead of the one you happened to get

Chapters
0: 00 Intro
0: 45 The idea
1: 17 The strategy and the trade record
1: 57 Pine has no random numbers
2: 36 The shuffle
3: 09 Two tables
3: 36 Running two hundred histories
4: 02 The drawdown histogram
4: 16 Reading it
4: 43 The number that proves it
5: 28 The real experiment
6: 00 What shuffling really measures
6: 43 The second test, which does change the answer
7: 11 Nineteen percent of futures lose
7: 53 What to do with it
8: 33 Two honest limits
9: 07 Your homework
9: 42 Recap

Full code: https://jayadevrana.in/free-pine-script-indicators/monte-carlo/

Educational content only. Not financial advice.

#PineScript #TradingView #PineScriptCourse