OPEN-SOURCE SCRIPT
Aggiornato

Trade Strategy Calculator [WillyAlgoTrader]

18 199
📊 Trade Strategy Calculator is the first comprehensive mathematical strategy calculator built entirely inside TradingView — a 4-panel dashboard that computes position sizing, risk analysis, deposit growth projection, and Kelly Criterion optimization in real time, directly on your chart. No spreadsheets, no external tools, no switching tabs. Every number you need before entering a trade — position size, stop loss level, take-profit targets, commission impact, expected value, probability of ruin, compound growth forecast, and optimal bet sizing — calculated from your strategy parameters and displayed in a single organized view.

This tool is useful for every trader regardless of market, instrument, or timeframe — stocks, forex, crypto, futures, indices, commodities. Whether you trade scalping on 1-minute charts or swing on daily, whether you use 1x spot or 125x futures leverage — the mathematics of position sizing, risk management, and bankroll growth are universal. This calculator puts those mathematics at your fingertips.


🧩 WHY ALL FOUR PANELS WORK TOGETHER

Most traders calculate position size in isolation — they know how much to risk but don't connect it to their long-term growth trajectory. They know their win rate but don't know if it's mathematically profitable after commissions. They have a "feel" for their risk level but haven't computed what happens after 7 consecutive losses.

This calculator connects four mathematical dimensions into one coherent picture:

🎯 TRADE panel answers: "How large should this specific trade be, and what are the exact entry/SL/TP prices?"
⚠️ RISK panel answers: "What happens when things go wrong — how many losses until I hit my daily limit, my max drawdown, and what's my expected value per trade?"
📈 GROWTH panel answers: "If I trade consistently with these parameters, where will my deposit be in 30/90/365 days — and how long to reach my target?"
📐 KELLY panel answers: "Am I betting the mathematically optimal amount — or am I over-betting (risking ruin) or under-betting (leaving growth on the table)?"

A trader who only uses the TRADE panel knows their position size but not whether their strategy has positive expected value. A trader who only uses KELLY knows the optimal bet size but not the specific position for their current trade. A trader who only uses GROWTH knows the projection but not whether the underlying math is sound. All four together give you the complete picture: "Is my strategy profitable? Am I sizing correctly? What's the worst case? And where does this lead?"


🔍 WHAT MAKES IT ORIGINAL

There is no other indicator on TradingView that combines all four of these mathematical models — position sizing, risk stress testing, compound growth simulation, and Kelly Criterion — into a single, real-time, interactive dashboard. Each panel alone would be a useful tool. Together, they create something that doesn't exist elsewhere on the platform.


🎯 PANEL 1 — TRADE (Position Sizing + Targets)

This panel calculates the exact position size for your trade based on your deposit, risk percentage, stop loss distance, leverage, and commissions.

Core formula:
positionSize = riskAmount / (slDistance% + commissionBothSides)

Where:
— riskAmount = deposit × riskPerTrade%
— slDistance% = slPercent × (1 + slippage%) — slippage is added to the stop distance for realistic sizing
— commissionBothSides = commission% × 2 (open + close)

This formula ensures that if your stop loss is hit, you lose exactly riskAmount — not more, not less — after accounting for both slippage and round-trip commission.

What you see:
— Direction (Long / Short)
— Entry Price (manual or auto from chart)
— Stop Loss price (calculated from entry ± SL%)
— 💰 Position Size in USD — the headline number
— Margin Required (if leverage > 1)
— Quantity (units/coins/shares)
— 🔴 Risk (loss) in USD and % of deposit
— 🟢 Profit at TP — in USD, % of deposit, and net R:R after commission
— TP Price level
— Commission cost in USD
— Liquidation price (for leveraged positions)
— ⚠️ Insufficient margin warning (if position exceeds deposit)

Multi Take-Profit mode:
When enabled, the position is split across 2 or 3 TP levels with configurable volume allocation:

— TP1 at R:R 1.0 with 50% of position → locks partial profit early
— TP2 at R:R 2.0 with 30% → captures the main move
— TP3 at R:R 3.0 with 20% (if 3 TPs) → runner for extended moves

Each TP shows: profit in USD, target price. The panel also computes:
— Total blended profit across all TPs
— Net R:R (blended, after commissions)
— Breakeven price after TP1 — the price where your remaining position becomes zero-loss after banking TP1 profit. This is critical: after TP1, you move your stop to this price — the trade can no longer lose money.

Example:
Deposit: $10,000. Risk: 1% ($100). SL: 2%. Commission: 0.04%.
Position = $100 / (0.02 + 0.0008) = $4,808.
If BTC at $100,000 → SL at $98,000, TP1 at $102,000.
If stopped out → you lose exactly $100 (1% of deposit).
If TP1 hit → you gain ~$96 (after commission).


⚠️ PANEL 2 — RISK (Stress Testing + Expected Value)

This panel answers: "What happens when I have a losing streak, and is my strategy mathematically profitable?"

Daily risk limit:
maxLosingDaily = floor(dailyRiskLimit% / riskPerTrade%)

Example: 3% daily limit, 1% per trade → you stop after 3 losses in a day.

Max drawdown limit:
maxLosingTotal = floor(maxDrawdown% / riskPerTrade%)

Example: 20% max DD, 1% per trade → 20 consecutive losses to hit max DD.

Stress test — losing streaks:
The panel computes what happens after 5, 7, and 10 consecutive losses:

— depositAfterN = deposit × (1 − riskPerTrade%)^N
— drawdownAfterN = (1 − (1 − riskPerTrade%)^N) × 100%
— probabilityOfN = (1 − winrate%)^N × 100%

Example: $10,000 deposit, 1% risk, 55% winrate:
— 5 losses: −4.9% DD ($9,510), probability 1.85%
— 7 losses: −6.8% DD ($9,321), probability 0.37%
— 10 losses: −9.6% DD ($9,044), probability 0.03%

This tells you: a 5-loss streak WILL happen (1.85% probability over hundreds of trades). A 10-loss streak is extremely rare (0.03%). Your risk% must be sized so that even the realistic worst case doesn't blow your account.

Expected Value (EV):
EV per trade = winrate × riskAmount × avgR:R − (1 − winrate) × riskAmount − commission

This is the single most important number in trading. If EV > 0, your strategy makes money over time. If EV < 0, no amount of position sizing saves you.

The panel shows:
— 📈 EV per trade in USD (highlighted — this is the headline metric)
— EV per 100 trades
— Break-even winrate WITH commission — the minimum winrate needed to be profitable at your R:R, accounting for commission drag
— Your actual WR and R:R for comparison

Break-even winrate formula (with commission):
beWinrate = (1 + commissionCost / riskAmount) / (avgR:R + 1)

This is more accurate than the standard 1/(R:R+1) because it accounts for commission reducing your net edge.


📈 PANEL 3 — GROWTH (Deposit Projection + Scenarios)

This is the unique deposit growth simulator — it projects where your deposit will be after N days of consistent trading, using either compound (reinvest profits) or simple (fixed risk from initial deposit) growth.

Compound growth formula:
EV per trade as % = winrate × (risk% × R:R) − (1 − winrate) × risk%
totalTrades = tradesPerDay × projectionDays
finalDeposit = deposit × (1 + evPerTrade%)^totalTrades

Simple growth formula:
finalDeposit = deposit + deposit × evPerTrade% × totalTrades

The difference is massive. Compound growth reinvests profits — each winning trade increases the base for the next trade. Simple growth always risks a fixed amount from the initial deposit.

Example — compound vs simple:
$1,000 deposit, 55% WR, 1:2 R:R, 1% risk, 3 trades/day, 30 days:
— Simple: $1,000 + $1,000 × 0.65% × 90 = $1,585
— Compound: $1,000 × (1.0065)^90 = $1,795

Over 90 days: $1,585 vs $1,795. Over 365 days the gap becomes enormous. This is why compound growth (reinvesting profits) is the key to deposit acceleration.

Three scenarios:
— 🟢 Optimistic: your winrate + 10% (what happens if you're having a great month)
— 🟡 Realistic: your actual parameters
— 🔴 Pessimistic: your winrate − 10% (what happens during a drawdown period)

This gives you a range, not a single number. If even the pessimistic scenario is positive, your strategy is robust.

Goal milestones:
— Days to 2× deposit (double your money)
— Days to 3× deposit
— Days to custom target ($5,000, $10,000, etc.)

Formula: daysToTarget = log(target / deposit) / (log(1 + evPerTrade%) × tradesPerDay)

Risk metrics:
— Max estimated drawdown: based on expected worst losing streak × risk%
— Ruin probability: the probability of losing your entire bankroll at your current risk level

Ruin probability formula:
edge = winrate × R:R − (1 − winrate)
bankrollUnits = floor(100 / risk%)
ruinProb = ((1 − winrate) / (winrate × R:R))^bankrollUnits

If edge ≤ 0, ruin probability is effectively 100%. If edge > 0, ruin probability decreases exponentially with more bankroll units (lower risk%).

Presets for quick scenarios:
— Beginner: 45% WR, 1:2 R:R, 1% risk — conservative starting point
— Moderate: 55% WR, 1:2 R:R, 2% risk — typical intermediate trader
— Aggressive: 50% WR, 1:3 R:R, 3% risk — higher risk, needs discipline
— Custom: uses your exact My Strategy values


📐 PANEL 4 — KELLY CRITERION (Optimal Bet Sizing)

The Kelly Criterion is the mathematically optimal percentage of your bankroll to risk on each bet, given your edge. It maximizes the long-term growth rate of your account.

Kelly formula:
edge = winrate × avgR:R − (1 − winrate)
kellyPercent = edge / avgR:R

If edge ≤ 0 → Kelly = 0% (no edge, don't trade). If edge > 0 → Kelly tells you the maximum you should risk.

What the panel shows:
— Your winrate and avg R:R
— Break-even winrate (with commission)
— 📐 Edge per $1 risked — your mathematical advantage. If +$0.15, every $1 risked returns $1.15 on average.
— Full Kelly % — the theoretical maximum. Most traders should NOT use this — it's too aggressive.
— Half Kelly ✦ — the recommended practical value. Reduces variance by ~75% while giving up only ~25% of growth.
— Quarter Kelly — ultra-conservative, minimal variance.
— Your current risk % — so you can compare
— Status: 🟢 Optimal (between half and full Kelly), 🟡 Conservative (below half), 🔴 Over-bet (above full Kelly), 🚨 >2× Kelly (danger zone)

Growth rate comparison:
— Growth rate at Kelly %: the compound growth rate per trade at the optimal bet size
— Growth rate at your %: your actual compound growth rate per trade

Formula: growthRate = winrate × log(1 + risk% × R:R) + (1 − winrate) × log(1 − risk%)

If your rate is close to the Kelly rate, you're near-optimal. If it's much lower, you're leaving growth on the table. If it's negative (possible when over-betting!), you're actually losing money despite having a positive edge — the over-betting destroys the compounding.

Why this matters:
A trader with a 55% WR and 1:2 R:R has an edge. Kelly says risk ~4.6%. But if that trader risks 10% per trade (2× Kelly), their actual growth rate can become negative — they go broke despite having a winning strategy. This is the most counterintuitive result in trading mathematics: over-betting a winning system turns it into a losing system. The Kelly panel prevents this.


📖 HOW TO USE — STEP BY STEP

Step 1 — Enter your strategy parameters (My Strategy section):
— Deposit: your actual account balance in USD
— Risk per Trade: how much you risk per trade (start with 1% if unsure)
— Winrate: your historical win rate (be honest — check your journal)
— Average R:R: your average reward-to-risk on winning trades
— Trades per Day: how many trades you typically take
— Leverage: 1 for spot, or your futures leverage
— Commission: your exchange fee per side (Binance Futures taker: 0.04%)

Step 2 — Set up your current trade (Trade Setup section):
— Direction: Long or Short
— Stop Loss %: how far your SL is from entry
— Risk:Reward: your target R:R for this trade
— Entry Price: manual or auto from chart

Step 3 — Read the TRADE panel:
— The 💰 Position Size number is your order size in USD
— If using leverage, check Margin Required doesn't exceed your deposit
— Note the SL and TP prices — set these in your exchange

Step 4 — Check the RISK panel:
— Is your EV per trade positive? If not, your strategy loses money long-term
— Is your winrate above the break-even? If not, improve your R:R
— Check the stress test: can your deposit survive 7 losses in a row?
— If the risk badge shows 🚨 DANGER, reduce your risk% or leverage

Step 5 — Review the GROWTH panel:
— The projected deposit shows where you'll be in 30 days
— Check the pessimistic scenario — is it still above your starting deposit?
— Note the days to 2× — this is your compound growth timeline
— If ruin probability > 5%, your risk is too high

Step 6 — Optimize with KELLY panel:
— Compare your risk% to Half Kelly — this is the recommended level
— If Status shows 🔴 Over-bet, reduce your risk%
— If Status shows 🟡 Conservative, you could increase (but don't have to)
— Check Growth Rate at Your % — is it positive? Is it close to Kelly's rate?


🎯 PRACTICAL EXAMPLES

Example 1 — Conservative Spot Trader:
Deposit $5,000, Risk 1%, WR 55%, R:R 1:2, 2 trades/day, No leverage, Commission 0.1%
— Position: ~$2,500 per trade. Risk: $50.
— EV: +$5.60 per trade. Positive — strategy is profitable.
— 30-day projection (compound): $5,000 → $5,705 (+14.1%)
— Days to double: ~98 days
— Kelly: 4.6%. Your 1% = conservative. Status: 🟡

Example 2 — Crypto Futures Scalper:
Deposit $1,000, Risk 2%, WR 50%, R:R 1:3, 5 trades/day, Leverage 10x, Commission 0.04%
— Position: ~$10,000 per trade. Margin: $1,000. Risk: $20.
— EV: +$10.40 per trade. Strong positive edge.
— 30-day projection (compound): $1,000 → $4,680 (+368%)
— Days to double: ~14 days
— Kelly: 8.3%. Your 2% = well below Kelly. Room to grow.
— ⚠️ But 7-loss streak probability: 0.78%. DD: −13.2%. Manageable.

Example 3 — Why Over-Betting Kills:
Same as Example 2, but Risk 15% (almost 2× Kelly):
— EV per trade still positive (+$78)
— BUT growth rate per trade: NEGATIVE (−0.3%)
— 30-day projection: $1,000 → $620 (−38%)
— Kelly Status: 🚨 >2× Kelly
— Despite winning 50% with 1:3 R:R, you LOSE money because over-betting destroys compounding.


⚙️ KEY SETTINGS REFERENCE

⚙️ My Strategy:
Deposit: account balance in USD
Risk per Trade (default 1%): % of deposit risked per trade
Winrate (default 55%): historical win rate
Average R:R (default 2.0): average reward-to-risk on wins
Trades per Day (default 3): daily trade count
Leverage (default 1): 1 = spot, >1 = futures
Commission (default 0.04%): exchange fee per side

🎯 Trade Setup:
Direction: Long / Short
Stop Loss % (default 1%): SL distance from entry
Risk:Reward (default 2.0): target R:R
Slippage (default 0.05%): expected execution slippage
Entry Price: Manual or Auto (chart price)

🎯 Multi Take-Profit:
Enable Multi TP (default Off): split into 2–3 targets
R:R for TP1/TP2/TP3 (default 1.0/2.0/3.0)
Volume allocation (default 50%/30%/20%)

📈 Growth Projection:
Preset: Beginner / Moderate / Aggressive / Custom
Projection Period (default 30 days)
Compound (default On): reinvest profits
Target Deposit (default 0 = off): goal amount
Max Daily Risk (default 3%): daily loss limit
Max Drawdown (default 20%): total DD limit

🎨 Visual:
— Font Size: Tiny / Small / Normal / Large
— Auto / Dark / Light theme


⚠️ IMPORTANT NOTES

— 📊 This is a calculator, not a signal generator. It does not produce buy/sell signals. It computes the mathematical framework for your trading decisions — position sizing, risk limits, growth projections, and optimal bet sizing. The math is universal and applies to any strategy.
— 📐 All calculations are deterministic — they depend only on your input parameters, not on price data. The dashboard updates in real-time when you change any input.
— ⚖️ The growth projection assumes consistent strategy parameters over the projection period. Real trading involves varying win rates, R:R ratios, and market conditions. The three scenarios (optimistic/realistic/pessimistic) partially address this by showing a range.
— 📏 The Kelly Criterion assumes known, fixed probabilities. In practice, your winrate and R:R fluctuate. This is why Half Kelly (not Full Kelly) is recommended — it accounts for parameter uncertainty.
— 💰 Commission is calculated as round-trip (both sides) and deducted from both profit calculations and expected value. This provides realistic net returns.
— 📊 The break-even winrate calculation includes commission drag — it's higher than the simplified 1/(R:R+1) formula because commission erodes your edge.
— 🔄 The compound growth formula uses logarithmic overflow protection — if the projected growth exceeds exp(23) ≈ 10 billion ×, it displays "∞" instead of crashing.
— 🛠️ Works on any chart, any instrument, any timeframe. The calculator is price-independent — it uses your manual inputs. "Auto" entry price mode uses the current chart close for convenience.
— 🌐 Useful for all markets: stocks (set leverage = 1, commission = 0.1%), forex (adjust for pip-based SL), crypto spot (leverage = 1), crypto futures (set your leverage), indices, commodities.
Note di rilascio
v3.3.1 — Accuracy & Consistency Update
This update is focused on one thing: every number on the dashboard now agrees with every other number.

📊 More accurate math

▪️ Expected Value, BE Winrate and Growth projections were refined — exchange commission is now applied consistently across all four sections. RISK and GROWTH panels now produce identical per-trade EV, verified against each other down to the cent.
▪️ Stop Loss price on the dashboard now shows your actual order level. Slippage still protects your position sizing, but no longer distorts the displayed SL — chart R:R now matches your input exactly.

⚙️ Compound toggle now rules everything

▪️ Stress test, daily/max-DD loss limits, Deposit x2/x3 horizons, Target date and Max DD estimate all respect the "Compound (reinvest profits)" setting. Previously some blocks silently assumed compounding regardless of your choice.
▪️ Worst losing-streak estimate now scales with your projection length — longer horizons correctly show deeper expected streaks.

📈 Scenarios reworked

▪️ Scenario rows now show explicit "WR +10% / WR −10%" labels instead of vague Optimistic/Pessimistic, duplicate row removed, and extreme-growth "∞" handling unified across all scenarios.

🎨 Polish

▪️ Auto theme detection now uses perceptual luminance — green/blue chart backgrounds are classified correctly.
▪️ 3-TP setup: warning now also fires when TP1+TP2 = exactly 100% (TP3 would get 0% volume).

As always — the model's assumptions are simplified projections, not guarantees. Trade your plan, not the forecast.

Declinazione di responsabilità

Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.