Monte Carlo Risk Calculator — Free Trading Calculator (Download, Runs in Your Browser)
- 39-monte-carlo-risk-calculator/index.html — the calculator page — open this in a browser
- 39-monte-carlo-risk-calculator/ui.mjs — the interface logic
- risk-calculators/risk.mjs — the calculation engine (risk)
- shared/style.css — the styles
- README-FIRST.md — what it does and how to run it
- FREE-LICENSE.md — the free-edition license terms
About this product
Monte Carlo Risk Calculator is a free trading calculator by Script Master Labs. It simulates thousands of trade sequences to show median and percentile outcomes, the drawdown distribution, and ruin probability. It runs entirely in your browser — no server, no account, and nothing you type leaves your device — and its complete source is printed in full on this page and in the free download. No payment, no account, no subscription.
What it computes, in its own terms: thousands of simulated trade sequences from your win rate and win/loss percentages: every trade wins or loses a percent of current equity, compounding trade by trade. The calculator reports the distribution of final equity (5th percentile, median, 95th percentile), the share of paths that ended profitable, the share that touched your ruin line (equity falling below the percent of start equity you set) at any point, and the distribution of each path's maximum drawdown. The simulation is seeded: the same seed always reproduces the same results exactly.
How to use it
Claim the free download, unzip it, and open the index.html inside the calculator's folder in any modern browser — it runs entirely on your device, with no install, no server and no account. The full source of every file is printed on this page below, and the free download carries the same working files with a README and the free-edition license.
Free edition vs paid edition
The download is the complete calculator — the same working files sold in the paid edition (https://dual.scriptmasterlabs.com/product/monte-carlo-risk-calculator, $19 one-time). The paid edition adds the full written user guide, the evidence receipt, and the licensing and security reviews. Nothing in the calculator is held back from the free edition.
More free tools — free Pine Script v6 indicators and strategies, free trading calculators and a free x402 pre-payment trust check — are collected on the Free Tools hub. Educational software, not financial advice: it computes stated formulas from your inputs; it does not predict price and shows no win rate.
The complete calculator source — free, on this page
Monte Carlo Risk Calculator is a free trading calculator by Script Master Labs. It simulates thousands of trade sequences to show median and percentile outcomes, the drawdown distribution, and ruin probability. It runs entirely in your browser — no server, no account, and nothing you type leaves your device — and its complete source is printed in full on this page and in the free download. No payment, no account, no subscription.
===== file: 39-monte-carlo-risk-calculator/index.html =====
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>Monte Carlo Risk Calculator | SML</title><meta name="description" content="Simulate thousands of trade sequences from a win rate and win/loss percentages: median and percentile outcomes, drawdown distribution, and ruin probability."><link rel="stylesheet" href="../shared/style.css"></head><body><main><h1>Monte Carlo Risk Calculator</h1><p>Simulate thousands of trade sequences from a win rate and win/loss percentages: median and percentile outcomes, drawdown distribution, and ruin probability.</p><form id="calc"><section class="inputs"><label>Starting equity ($)<input name="startEquity" type="number" step="any" required></label><label>Win rate (%)<input name="winRatePercent" type="number" step="any" required></label><label>Win size (% of equity)<input name="winPercent" type="number" step="any" required></label><label>Loss size (% of equity)<input name="lossPercent" type="number" step="any" required></label><label>Trades per path<input name="trades" type="number" step="any" required></label><label>Simulations<input name="simulations" type="number" step="any" value="1000" required></label><label>Random seed<input name="seed" type="number" step="any" value="42" required></label><label>Ruin line (% of start equity)<input name="ruinLinePercent" type="number" step="any" value="50" required></label></section><button type="submit">Calculate</button></form><p id="error" role="alert"></p><section id="results" hidden><h2>Results</h2><div id="metrics"></div><button id="export">Export JSON</button></section><section><h2>How this is calculated</h2><p>Each simulated path plays the trade sequence you describe: every trade wins winPercent of current equity with probability equal to your win rate, or loses lossPercent of current equity, compounding trade by trade. The calculator runs the number of simulations you set and reports the distribution of final equity (5th percentile, median, 95th percentile), the share of paths that ended profitable, the share that touched the ruin line (equity falling below the percent of start equity you set) at any point, and the distribution of each path's maximum drawdown (median and 95th percentile). The simulation is seeded: the same seed always reproduces the same results exactly, and the guide's worked example can be re-run to the cent.</p><p>Limitations: The simulation treats trades as independent draws at fixed win/loss percentages — real strategies have varying trade sizes, correlated losses, and regime changes, all of which widen real outcome spreads beyond what is shown here. Win and loss percentages of current equity mean position size is assumed to scale with equity. Percentiles describe this simplified model only; they are not probabilities about your actual future account. This calculator is not financial advice.</p></section></main><script type="module" src="ui.mjs"></script></body></html>
===== file: 39-monte-carlo-risk-calculator/ui.mjs =====
import {monteCarloRisk} from '../risk-calculators/risk.mjs';const form=document.querySelector('#calc'),results=document.querySelector('#results'),metrics=document.querySelector('#metrics'),error=document.querySelector('#error');let last=null;form.addEventListener('input',()=>{last=null;results.hidden=true;error.textContent=''});form.addEventListener('submit',e=>{e.preventDefault();last=null;results.hidden=true;error.textContent='';try{const inputs=Object.fromEntries([...new FormData(form)].map(([k,v])=>[k,k==='side'?v:Number(v)]));const output=monteCarloRisk(inputs);metrics.replaceChildren();for(const [k,v] of Object.entries(output)){const d=document.createElement('div');d.className='metric';d.textContent=k.replace(/([A-Z])/g,' $1');const s=document.createElement('strong');s.textContent=v===null?'Undefined':typeof v==='number'?v.toLocaleString('en-US',{maximumFractionDigits:4}):String(v);d.append(s);metrics.append(d)}last={inputs,output};results.hidden=false}catch(e){error.textContent=e.message}});document.querySelector('#export').onclick=()=>{if(!last)return;const url=URL.createObjectURL(new Blob([JSON.stringify(last,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='39-monte-carlo-risk-calculator.json';a.click();URL.revokeObjectURL(url)};
===== file: risk-calculators/risk.mjs =====
export function positionSize({equity,riskPercent,entry,stop,feesPerShare=0,fixedFees=0,availableCapital=equity,side='long'}){
if(![equity,riskPercent,entry,stop,feesPerShare,fixedFees,availableCapital].every(Number.isFinite)||equity<=0||riskPercent<=0||riskPercent>100||entry<=0||stop<0||feesPerShare<0||fixedFees<0||availableCapital<0||!['long','short'].includes(side)||(side==='long'?stop>=entry:stop<=entry))throw new RangeError('Invalid position inputs');
const budget=equity*riskPercent/100,unitRisk=Math.abs(entry-stop)+feesPerShare;
const riskLimit=Math.max(0,Math.floor((budget-fixedFees)/unitRisk));
const capitalLimit=Math.max(0,Math.floor((availableCapital-fixedFees)/(entry+feesPerShare)));
const shares=Math.min(riskLimit,capitalLimit);
if(!Number.isSafeInteger(shares))throw new RangeError('Size overflow');
return {shares,budget,unitRisk,plannedLoss:shares?shares*unitRisk+fixedFees:0,notional:shares*entry,riskLimit,capitalLimit};
}
export function rewardRisk({entry,stop,target,side='long',costPerShare=0}){
if(![entry,stop,target,costPerShare].every(Number.isFinite)||entry<=0||stop<0||target<0||costPerShare<0||!['long','short'].includes(side))throw new RangeError('Invalid trade');
const d=side==='long'?1:-1,risk=d*(entry-stop)+costPerShare,reward=d*(target-entry)-costPerShare;
if(d*(entry-stop)<=0||reward<=0)throw new RangeError('Invalid stop or net target');
return {risk,reward,ratio:reward/risk,breakEvenWinRate:risk/(risk+reward)};
}
export function drawdown({peak,current}){
if(![peak,current].every(Number.isFinite)||peak<=0||current<0||current>peak)throw new RangeError('Invalid equity');
return {loss:peak-current,drawdownPercent:(peak-current)/peak*100,recoveryPercent:current===0?null:(peak-current)/current*100};
}
export function spreadSlippage({bid,ask,side='buy',shares,benchmark,fill,commission=0}){
if(![bid,ask,shares,benchmark,fill,commission].every(Number.isFinite)||bid<=0||ask<bid||shares<=0||benchmark<=0||fill<=0||commission<0||!['buy','sell'].includes(side))throw new RangeError('Invalid spread or fill inputs');
const mid=(bid+ask)/2,spread=ask-bid,dir=side==='buy'?1:-1;
const slippagePerShare=dir*(fill-benchmark);
const slippageTotal=slippagePerShare*shares;
return {mid,spread,spreadPercent:spread/mid*100,spreadBps:spread/mid*10000,halfSpreadPerShare:spread/2,halfSpreadTotal:spread/2*shares,slippagePerShare,slippagePercent:slippagePerShare/benchmark*100,slippageBps:slippagePerShare/benchmark*10000,slippageTotal,effectiveSpreadPerShare:2*Math.abs(fill-mid),commission,totalCost:slippageTotal+commission};
}
export function compounding({principal,ratePercent,periods,contribution=0}){
if(![principal,ratePercent,periods,contribution].every(Number.isFinite)||principal<=0||ratePercent<=-100||!Number.isInteger(periods)||periods<1||contribution<0)throw new RangeError('Invalid compounding inputs');
const r=ratePercent/100,growth=Math.pow(1+r,periods);
const fromPrincipal=principal*growth;
const fromContributions=r===0?contribution*periods:contribution*((growth-1)/r);
const finalBalance=fromPrincipal+fromContributions,totalContributions=contribution*periods;
if(!Number.isFinite(finalBalance))throw new RangeError('Projection overflow');
const totalGain=finalBalance-principal-totalContributions;
return {finalBalance,fromPrincipal,fromContributions,totalContributions,totalGain,totalReturnPercent:totalGain/(principal+totalContributions)*100};
}
export function kellyCriterion({winRatePercent,avgWin,avgLoss,bankroll}){
if(![winRatePercent,avgWin,avgLoss,bankroll].every(Number.isFinite)||winRatePercent<=0||winRatePercent>=100||avgWin<=0||avgLoss<=0||bankroll<=0)throw new RangeError('Invalid Kelly inputs');
const p=winRatePercent/100,q=1-p,b=avgWin/avgLoss,f=p-q/b;
const edge=f>0,fc=edge?f:0;
const logGrowth=edge&&f<1?p*Math.log(1+f*b)+q*Math.log(1-f):null;
return {payoffRatio:b,fullKellyPercent:f*100,halfKellyPercent:f*50,quarterKellyPercent:f*25,stakeFull:fc*bankroll,stakeHalf:fc/2*bankroll,stakeQuarter:fc/4*bankroll,edge,logGrowthPerTrade:logGrowth,growthPercentPerTrade:logGrowth===null?null:(Math.exp(logGrowth)-1)*100,verdict:edge?'Inputs imply a positive Kelly fraction':'No bet — the inputs imply no positive edge (Kelly fraction is zero or negative)'};
}
export function expectancy({winRatePercent,avgWin,avgLoss,trades=100}){
if(![winRatePercent,avgWin,avgLoss,trades].every(Number.isFinite)||winRatePercent<=0||winRatePercent>=100||avgWin<=0||avgLoss<=0||!Number.isInteger(trades)||trades<1)throw new RangeError('Invalid expectancy inputs');
const p=winRatePercent/100,q=1-p,e=p*avgWin-q*avgLoss;
return {expectancyPerTrade:e,expectancyR:e/avgLoss,profitFactor:(p*avgWin)/(q*avgLoss),breakevenWinRatePercent:avgLoss/(avgWin+avgLoss)*100,totalForTrades:e*trades,trades};
}
export function atrStopLoss({entry,atr,multiplier=2,side='long',riskBudget=null,shares=null}){
if(![entry,atr,multiplier].every(Number.isFinite)||entry<=0||atr<=0||multiplier<=0||!['long','short'].includes(side)||(riskBudget!==null&&(!Number.isFinite(riskBudget)||riskBudget<=0))||(shares!==null&&(!Number.isFinite(shares)||shares<=0)))throw new RangeError('Invalid ATR stop inputs');
const distance=atr*multiplier,stopPrice=side==='long'?entry-distance:entry+distance;
if(stopPrice<=0)throw new RangeError('Stop price would be zero or negative — distance exceeds entry');
const out={distance,stopPrice};
if(riskBudget!==null){out.sharesForBudget=Math.floor(riskBudget/distance);out.notionalForBudget=out.sharesForBudget*entry;out.actualRiskForBudget=out.sharesForBudget*distance;}
if(shares!==null){out.riskForShares=shares*distance;out.notionalForShares=shares*entry;}
return out;
}
export function shortSqueezeScore({shortInterestPercent,daysToCover,borrowFeePercent,shortInterestChangePercent,floatMillions}){
if(![shortInterestPercent,daysToCover,borrowFeePercent,shortInterestChangePercent,floatMillions].every(Number.isFinite)||shortInterestPercent<0||shortInterestPercent>100||daysToCover<0||borrowFeePercent<0||shortInterestChangePercent<-100||floatMillions<=0)throw new RangeError('Invalid short-squeeze inputs');
const band=(v,table)=>{for(const [limit,pts] of table)if(v>=limit)return pts;return table[table.length-1][1];};
const si=shortInterestPercent===0?0:band(shortInterestPercent,[[30,30],[20,24],[15,19],[10,14],[5,8],[0,3]]);
const dtc=daysToCover===0?0:band(daysToCover,[[10,25],[7,20],[5,16],[3,11],[1,6],[0,2]]);
const fee=band(borrowFeePercent,[[50,20],[25,16],[10,12],[5,7],[1,3],[0,1]]);
const chg=shortInterestChangePercent>=0?band(shortInterestChangePercent,[[25,15],[10,11],[0,6]]):(shortInterestChangePercent>-10?3:0);
const flt=floatMillions<20?10:floatMillions<=50?8:floatMillions<=100?6:floatMillions<=250?3:1;
const total=si+dtc+fee+chg+flt;
return {siPoints:si,dtcPoints:dtc,feePoints:fee,changePoints:chg,floatPoints:flt,totalScore:total,bandLabel:total>=75?'High':total>=50?'Elevated':total>=25?'Moderate':'Low'};
}
export function monteCarloRisk({startEquity,winRatePercent,winPercent,lossPercent,trades,simulations,seed=42,ruinLinePercent=50}){
if(![startEquity,winRatePercent,winPercent,lossPercent,trades,simulations,seed,ruinLinePercent].every(Number.isFinite)||startEquity<=0||winRatePercent<=0||winRatePercent>=100||winPercent<=0||lossPercent<=0||lossPercent>=100||!Number.isInteger(trades)||trades<1||trades>2000||!Number.isInteger(simulations)||simulations<10||simulations>10000||!Number.isInteger(seed)||seed<0||ruinLinePercent<=0||ruinLinePercent>=100)throw new RangeError('Invalid Monte Carlo inputs');
let state=seed%4294967296;const rnd=()=>{state=(1664525*state+1013904223)%4294967296;return state/4294967296;};
const p=winRatePercent/100,w=1+winPercent/100,l=1-lossPercent/100,ruinLine=startEquity*ruinLinePercent/100;
const finals=[],maxDDs=[];let ruined=0,profitable=0;
for(let s=0;s<simulations;s++){let eq=startEquity,peak=eq,mdd=0,hit=false;
for(let t=0;t<trades;t++){eq*=rnd()<p?w:l;if(eq>peak)peak=eq;const dd=(peak-eq)/peak;if(dd>mdd)mdd=dd;if(eq<ruinLine)hit=true;}
finals.push(eq);maxDDs.push(mdd*100);if(hit)ruined++;if(eq>startEquity)profitable++;}
finals.sort((a,b)=>a-b);maxDDs.sort((a,b)=>a-b);
const pct=(a,pp)=>a[Math.ceil(pp/100*a.length)-1];
return {medianFinal:pct(finals,50),p5Final:pct(finals,5),p95Final:pct(finals,95),percentProfitable:profitable/simulations*100,ruinProbabilityPercent:ruined/simulations*100,medianMaxDrawdownPercent:pct(maxDDs,50),p95MaxDrawdownPercent:pct(maxDDs,95),simulations,trades,seed};
}
===== file: shared/style.css =====
*{box-sizing:border-box}body{margin:0;background:#000;color:#fff;font:16px system-ui}main{max-width:1100px;margin:auto;padding:20px}section{border:1px solid #343434;border-radius:12px;padding:16px;margin:16px 0}h1{font-size:clamp(26px,5vw,42px)}h2{font-size:20px}label{display:grid;gap:6px}input,select,button{font:inherit;color:#fff;background:#121212;border:1px solid #777;border-radius:7px;padding:10px;min-width:0;width:100%}button{background:#123b31;cursor:pointer;width:auto;min-height:44px}button:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid #5eead4}.leg,.inputs,#metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:12px}.leg{padding:12px 0;border-bottom:1px solid #444}.metric{padding:12px;border:1px solid #555;border-radius:8px;overflow-wrap:anywhere}.metric strong{display:block;font-size:20px;margin-top:6px}svg{width:100%;height:auto;background:#080808;margin-top:16px}#error{color:#ff9494}p{line-height:1.5}.scroll{overflow-x:auto}table{border-collapse:collapse;width:100%;margin-top:12px;font-size:14px}th,td{border:1px solid #343434;padding:8px;text-align:right;white-space:nowrap}th{background:#121212}td.pos{color:#5eead4}td.neg{color:#ff9494}td.base{background:#123b31;font-weight:700}
Questions about this product
Is there a free Monte Carlo trading risk calculator I can download?
Yes. Script Master Labs publishes this Monte Carlo Risk Calculator as a free download on SML Dual Market (https://dual.scriptmasterlabs.com/product/free-monte-carlo-risk-calculator). The complete calculator — the same working files sold in the paid edition — is in the free download, and its full source is printed on the product page. No payment, no account, no subscription.
How do I use the Monte Carlo Risk Calculator?
Claim the free download, unzip it, and open the index.html inside the calculator's folder in any modern browser. Type your numbers and press Calculate. There is nothing to install.
Does the calculator send my numbers anywhere?
No. It runs entirely in your browser on your own device: no server, no account, no feed. The numbers you type never leave your device.
Is the free edition the complete calculator?
Yes — the same working files sold in the paid edition ($19 one-time). The paid edition adds the full written user guide, the evidence receipt, and the licensing and security reviews; nothing in the calculator itself is held back.