OPEN-SOURCE SCRIPT

Risk Simulation [Monte Carlo]

1 729
RISK SIMULATION [MONTE CARLO]
This indicator is an analytical tool designed to measure the mathematical viability of a specific trade setup and model the potential scenarios that could occur if one remains loyal to that setup.

This is NOT a Backtester
Classic backtest indicators report the performance of a trading system based on past price action. Risk Simulation, however, does not need price action; it calculates the performance distribution of a system based on its fundamental inputs (Win Rate, Reward/Risk). In this sense, risk simulations are mathematical probability models that allow us to foresee potential scenarios before entering the market. The main idea is to model the probable outcomes of a system designed with the available setup information/decisions.

HOW IT WORKS
To understand how this indicator works without getting lost in complex code, imagine this scenario:
You tell the Pine Script compiler: "I have a coin that lands on heads 35% of the time. If it's heads, I win $2.5; if it's tails, I lose $1. Now, flip this coin 5,000 times and report the statistical distribution."

MECHANICS
The technical structure of this tool is built for repeatability, utilizing a deterministic approach instead of standard pseudo-random generators:
• LCG Implementation (f_random): The script uses a Linear Congruential Generator based on Knuth and Park-Miller parameters to produce a consistent distribution.
• Seed-Based Randomness: Through the "Scenario ID" (Seed input), the engine ensures that the trade sequence remains identical across script recalculations.
• Variable Risk Model (f_simulate_trade): For each trade, a random stop-loss is assigned between the "Min" and "Max" range to calculate commission and position sizing dynamically.
• Data Management (f_run_simulation): Simulation cycles and metrics (Sharpe, Sortino, Kelly, etc.) are processed using matrix and array structures for computational efficiency.
• Percentile Interpolation (f_get_column_stats): Instead of rank-based selection, array.percentile_linear_interpolation is used to calculate the Median and Custom P% results.

HOW TO USE
The indicator requires a few core inputs to model your trading "profile":
• Setup: Define your starting capital, the percentage of risk you take per trade (compounding), your average Win Rate, and your Reward-to-Risk (R) ratio.
• Commission: Enter the percentage fee your broker charges. This is applied to both entry and exit prices for every simulated trade.
• Stops: Set a range for your stop-loss distance. This helps the model simulate how varying market volatility affects your position sizing and net profit.
• Simulation Count: Define how many "alternative futures" you want to generate. You can increase this up to 5000 for a broader statistical sample.
• Circuit Breaker: Set the percentage of capital loss that you consider "bankruptcy." If a simulation hits this level, it stops and is recorded as a "ruin" event.

OUTPUTS
The simulation results are presented in a comparative table that breaks down the performance distribution across various scenarios. Instead of a single backtest result, the table displays the Worst, Median, Best, and Mean outcomes, along with a user-defined percentile (P%) for statistical interpolation. The reporting focuses on three core areas:
• Account Dynamics: Tracks total PnL and equity evolution to show the final balance distribution.
• Risk & Survival: Highlights the Max Drawdown experienced and the Risk of Ruin (RoR), which calculates the probability of hitting your defined bankruptcy threshold.
• Performance Quality: Evaluates the trade model through risk-adjusted return ratios (Sharpe, Sortino) and system quality metrics like the SQN score and Kelly Ratio for position sizing.

DISCLAIMER
This indicator is a mathematical modeling tool based on probability theory. It does not account for market liquidity, slippage, execution errors, or the psychological challenges of live trading. The results are simulations of a specific mathematical model and should be used as a supplementary tool for risk management and strategy evaluation, not as a guarantee of future performance.

Aviso legal

As informações e publicações não se destinam a ser, e não constituem, conselhos ou recomendações financeiras, de investimento, comerciais ou de outro tipo fornecidos ou endossados pela TradingView. Leia mais nos Termos de Uso.